swift——复合类型——函数——函数类型
2017-05-16 21:01
148 查看
函数类型
函数类型由参数类型和返回类型组成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 nothing feed rice 5 feed 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: 26 result: 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: 26 result: 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: 26 result: 10
相关文章推荐
- swift——复合类型——函数——参数 返回类型
- swift——复合类型——函数——闭包
- Swift基础语法: 23 - Swift的闭包简介, Sorted函数, 闭包的表达式语法, 根据上下文推断类型, 参数名简写, 运算符函数
- swift复合类型
- 4.swift 知识点积累 as 闭包和函数类型
- 5.8 Swift函数类型
- Swift 函数也有类型type
- Swift函数类型
- cpp——复合类型——函数——匿名形参 默认实参
- swift基本语法(总结提炼版)之011 swift 之函数类型
- Swift语法_函数类型
- Go语言圣经:基础数据类型、复合数据类型、函数、方法章节摘录
- Swift2.0语言教程之函数的返回值与函数类型
- swift中函数的类型
- 浅谈swift中的函数类型和闭包
- Swift可选类型在函数中的使用
- 【swift】15-0529 In-Out参数 函数类型
- swift学习之函数类型
- Swift---- 可选值类型(Optionals) 、 断言(Assertion) 、 集合 、 函数
- swift 函数、函数类型及使用——swift学习(五)