前面我们讲解了函数里面的形参,现在让我们继续来看看函数的类型,以及嵌套函数,让我们一起来看看:
1.使用函数类型
在Swift中的函数声明和在OC中没什么区别,只有语法上的差异,但在Swift中有一项比较有趣的就是,声明变量或者常量的时候也是可以指定返回值的,比如:
- func addTwoInts(a: Int,b: Int) -> Int {
- return a + b
- }
-
- var mathFunction: (Int,Int) -> Int = addTwoInts
-
- var math = mathFunction(1,2)
- println(math)
- // 打印出来的结果: 3
当然,常量也是可以如此的,这里就不多做解释了,想知道的朋友可以自己回去试试.
2.作为形参类型的函数类型
还有更好玩的就是,我们可以在声明新的函数时,把这个变量当成形参传入进去,b: Int) -> Int { return a + b } func printMathResult(mathFunction: (Int,Int) -> Int,a: Int,b: Int) { println("Result: \(mathFunction(a,b))") } printMathResult(addTwoInts,3,5) // 打印出来的结果: 8
PS: 首先我们来看看,第一个函数addTwoInts是用来计算两个形参之和,而第二个函数,用来打印他们之后,在调用的时候,我们传入运算函数addTwoInts,然后在把3,5传入,然后两个整数就会去addTwoInts 里运算,再把结果返回,最后再由printMathResult函数打印出来.
3.作为返回类型的函数类型
上面,我们看到了作为形参的例子,下面来看看作为返回类型的函数类型,比如:
- func stepForward(input: Int) -> Int {
- return input + 1
- }
- func stepBackward(input: Int) -> Int {
- return input - 1
- }
-
- func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
- return backwards ? stepBackward : stepForward
- }
-
- var currentValue = 3
- let moveNearerToZero = chooseStepFunction(currentValue > 0)
-
- println("Counting to zero:")
-
- while currentValue != 0 {
- println("\(currentValue)... ")
- currentValue = moveNearerToZero(currentValue)
- }
-
- println("zero!")
- // 打印出来的结果: Counting to zero:
- // 3...
- // 2...
- // 1...
- // zero!
PS: 解释一下该例子,前面的例子可以计算出是否需要通过递增或者递减来让 currentValue 变量趋于零,currentValue 的初始值为 3,这意味着 currentValue > 0 返回为真,并且 chooseStepFunction 返回 stepBackward 函数,返回函数的引用存储在一个名为moveNearerToZero 的常量里,其类型准确说来是:接受一个Bool型参数,并返回一个函数,该函数接受一个Int型变量并返回一个Int值.
4.嵌套函数
到现在为止,我们遇到的函数都是全局函数,在全局作用域中定义,其实我们还可以在其他函数体中定义函数,被称为嵌套函数,比如:
- func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
-
- func stepForward(input: Int) -> Int { return input + 1 }
- func stepBackward(input: Int) -> Int { return input - 1 }
-
- return backwards ? stepBackward : stepForward
- }
-
- var currentValue = -4
- let moveNearerToZero = chooseStepFunction(currentValue > 0)
- while currentValue != 0 {
- println("\(currentValue)... ")
- currentValue = moveNearerToZero(currentValue)
- }
- println("zero!")
- // 打印出来的结果: -4...
- // -3...
- // -2...
- // -1...
- // zero!
PS: 这样子的做法就是把stepForward和stepBackward两个函数作用于chooseStepFunction函数之中,在外面都是不可调用的.
好了,这次我们就讲到这里,下次我们继续~