Swift基础语法: 22 - Swift的函数类型, 嵌套函数

前端之家收集整理的这篇文章主要介绍了Swift基础语法: 22 - Swift的函数类型, 嵌套函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前面我们讲解了函数里面的形参,现在让我们继续来看看函数的类型,以及嵌套函数,让我们一起来看看:


1.使用函数类型

在Swift中的函数声明和在OC中没什么区别,只有语法上的差异,但在Swift中有一项比较有趣的就是,声明变量或者常量的时候也是可以指定返回值的,比如:

  1. func addTwoInts(a: Int,b: Int) -> Int {
  2. return a + b
  3. }
  4.  
  5. var mathFunction: (Int,Int) -> Int = addTwoInts
  6.  
  7. var math = mathFunction(1,2)
  8. println(math)
  9. // 打印出来的结果: 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.作为返回类型的函数类型

上面,我们看到了作为形参的例子,下面来看看作为返回类型的函数类型,比如:

  1. func stepForward(input: Int) -> Int {
  2. return input + 1
  3. }
  4. func stepBackward(input: Int) -> Int {
  5. return input - 1
  6. }
  7.  
  8. func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
  9. return backwards ? stepBackward : stepForward
  10. }
  11.  
  12. var currentValue = 3
  13. let moveNearerToZero = chooseStepFunction(currentValue > 0)
  14.  
  15. println("Counting to zero:")
  16.  
  17. while currentValue != 0 {
  18. println("\(currentValue)... ")
  19. currentValue = moveNearerToZero(currentValue)
  20. }
  21.  
  22. println("zero!")
  23. // 打印出来的结果: Counting to zero:
  24. // 3...
  25. // 2...
  26. // 1...
  27. // zero!

PS: 解释一下该例子,前面的例子可以计算出是否需要通过递增或者递减来让 currentValue 变量趋于零,currentValue 的初始值为 3,这意味着 currentValue > 0 返回为真,并且 chooseStepFunction 返回 stepBackward 函数,返回函数的引用存储在一个名为moveNearerToZero 的常量里,其类型准确说来是:接受一个Bool型参数,并返回一个函数,该函数接受一个Int型变量并返回一个Int值.


4.嵌套函数

到现在为止,我们遇到的函数都是全局函数,在全局作用域中定义,其实我们还可以在其他函数体中定义函数,被称为嵌套函数,比如:

  1. func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
  2.  
  3. func stepForward(input: Int) -> Int { return input + 1 }
  4. func stepBackward(input: Int) -> Int { return input - 1 }
  5.  
  6. return backwards ? stepBackward : stepForward
  7. }
  8.  
  9. var currentValue = -4
  10. let moveNearerToZero = chooseStepFunction(currentValue > 0)
  11. while currentValue != 0 {
  12. println("\(currentValue)... ")
  13. currentValue = moveNearerToZero(currentValue)
  14. }
  15. println("zero!")
  16. // 打印出来的结果: -4...
  17. // -3...
  18. // -2...
  19. // -1...
  20. // zero!

PS: 这样子的做法就是把stepForward和stepBackward两个函数作用于chooseStepFunction函数之中,在外面都是不可调用的.


好了,这次我们就讲到这里,下次我们继续~

猜你在找的Swift相关文章