swift——复合类型——函数——函数类型
来源:互联网 发布:怎么能开淘宝店铺 编辑:程序博客网 时间:2024/05/17 05:55
函数类型
函数类型由参数类型和返回类型组成
func feed(){ print("feed nothing")}func feed(rice: Int) -> Int{ print("feed rice \(rice)") return rice;}func feed(rice: Int, meat: Int) -> (Int, Int){ print("feed rice \(rice) and meat \(meat)") return (rice, meat)}func use_functype(){ let feed0: () -> Void = feed let feed1: (Int) -> Int = feed let feed2: (Int, Int) -> (Int, Int) = feed feed0(); feed1(5) feed2(5, 8)}
output:
feed nothingfeed rice 5feed rice 5 and meat 8
总结:
- 函数类型的返回类型本质为tuple,因此空tuple可用Void或()表示,但不可omit,只含单个成员tuple括号optional,包含多个成员tuple括号不可omit
- 函数类型的参数类型本质为tuple,因此空tuple可用Void或()表示,但不可omit,只含单个成员tuple括号optional,包含多个成员tuple括号不可omit
- 函数类型在使用上与普通类型(如Int)无任何区别,可使用let或var定义,亦可进行类型推断,只要不造成二义性error
- 函数名本质就是函数类型,只是常量(let)而已,函数定义时即进行了初始化,指向所定义函数
函数类型参数
func add(a: Int, _ b: Int) -> Int{ return a + b}func sub(a: Int, _ b: Int) -> Int{ return a - b}func arith(fun: (Int, Int) -> Int, _ a: Int, _ b: Int){ print("result: \(fun(a, b))")}func functype_param(){ arith(add, 18, 8) arith(sub, 18, 8)}
output:
result: 26result: 10
函数类型返回值
func add(a: Int, _ b: Int) -> Int{ return a + b}func sub(a: Int, _ b: Int) -> Int{ return a - b}func arith(flag: Bool) -> (Int, Int) -> Int{ if(flag) { return add } else { return sub }}func functype_ret(){ let fun1 = arith(true) let fun2 = arith(false) print("result: \(fun1(18, 8))") print("result: \(fun2(18, 8))")}
output:
result: 26result: 10
嵌套函数
func arith(flag: Bool) -> (Int, Int) -> Int{ func add(a: Int, _ b: Int) -> Int { return a + b } func sub(a: Int, _ b: Int) -> Int { return a - b } if(flag) { return add } else { return sub }}func nested_func(){ let fun1 = arith(true) let fun2 = arith(false) print("result: \(fun1(18, 8))") print("result: \(fun2(18, 8))")}
output:
result: 26result: 10
阅读全文
0 0
- swift——复合类型——函数——函数类型
- swift——复合类型——函数——参数 返回类型
- swift——复合类型——函数——闭包
- c——复合类型——函数
- swift——运算符——复合类型
- swift——复合类型——tuple
- swift——复合类型——String
- swift——复合类型——Array
- swift——复合类型——Set
- swift——复合类型——Dict
- 复合类型 —— 引用
- 复合类型 —— 指针
- cpp——复合类型——函数——函数重载
- Swift学习笔记(三十四)——函数类型
- swift 函数、函数类型及使用——swift学习(五)
- c——复合类型——函数——可变参数
- cpp——复合类型——函数——匿名形参 默认实参
- cpp——复合类型——函数——运算符重载
- [深度学习论文笔记][CVPR 17]RefineNet: Multi-Path Refinement Networks for High-Resolution Semantic
- Python与MATLAB:随机打乱一个数字序列
- SDOI2017 Round2 退役记
- Kill Process
- [PAT-乙级]1035.插入与归并
- swift——复合类型——函数——函数类型
- 数据挖掘十大算法
- C++ 函数
- 动态代理源码解析之JDK
- Java8 实战学习 — Lambda 表达式
- redhat5.5 安装 glibc2.18 步骤及问题小结
- js中substring()与substr()方法的区别
- Hibernate(五):Hibernate映射——一对一单向关联映射
- 欢迎使用CSDN-markdown编辑器