swift 闭包 由浅入深 优化

前端之家收集整理的这篇文章主要介绍了swift 闭包 由浅入深 优化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. //: Playground - noun: a place where people can play
  2.  
  3. import UIKit
  4. /////////////////////////////////////////// // //func sorted(isOrderedBefore:(T,T)->Bool) -> [T]{ // //}
  5.  
  6. let animals = ["fish","cat","chicken","dog"]
  7. //func isOrderedBefore(one : String,two: String) -> Bool //{ // return one < two //} // //let sortedString = animals.sort(isOrderedBefore)
  8. // 与排序 小于号 ,传递核心代码
  9.  
  10. let sortedString = animals.sort({(one: String,two: String) -> Bool in
  11. return one < two
  12.  
  13. })
  14. // 在sort 函数里面传递了参数 而参数又是一个函数 ,这个函数就叫做闭包
  15. // 闭包 没有完整的函数声明 有参数列表 one: String,two: String // in关键字后面是闭包的实现代码
  16. // 编译器可以断言出参数的类型
  17. let sortedString2 = animals.sort({(one,two) -> Bool in
  18. return one < two
  19.  
  20. })
  21. // -> Bool 返回值信息也可以 删除掉 这个信息可以再sort的声明中得到< sort 声明>
  22. let sortedString3 = animals.sort({(one,two) in
  23. return one < two
  24.  
  25. })
  26.  
  27. // 没有返回值类型->bool声明以后 ()也可以去除
  28.  
  29. let sortedString4 = animals.sort({one,two in
  30. return one < two
  31.  
  32. })
  33. // 可以省略执行代码的return语句 编译器已经断言出来返回值是bool 类型 //所执行代码一行,删除return 语句
  34.  
  35. let sortedString5 = animals.sort({one,two in
  36. one < two
  37. })
  38. //接下来我们还可以省略参数 // one two 没有意义 用参数本地常量进行代替
  39.  
  40. let sortedString6 = animals.sort({$0 < $1})
  41. //如果传递的闭包是方法或者函数的最后一个参数, 可以将闭包放到闭包的外面 //称为结尾闭包
  42.  
  43. let sortedString7 = animals.sort(){$0 < $1}
  44. print(sortedString7)
  45. // 还可以移除没有参数的括号
  46. let sortedString8 = animals.sort{$0 < $1}
  47. print(sortedString8)
  48. //把花括号替换为小括号 只写一个 < 闭包神奇之处
  49. let sortedString9 = animals.sort(>)
  50. print(sortedString9) //---------------------------------------------- //闭包还可以捕获 上下文中常量或者变量的数值 //甚至原始环境销毁也可以使用
  51.  
  52. typealias stateMachineType = () ->Int
  53.  
  54. func makeStateMachine(maxState: Int) -> stateMachineType{
  55.  
  56. var currentState: Int = 0
  57.  
  58. return{
  59. currentState++
  60. if currentState > maxState{
  61. currentState = 0
  62. }
  63. return currentState
  64. }
  65. }
  66.  
  67. let tt = makeStateMachine(2)
  68.  
  69. print(tt())
  70.  
  71. print(tt())
  72.  
  73. print(tt())
  74.  
  75. print(tt())
  76.  
  77. print(tt())
  78.  
  79. // 不管makeStateMachine 是否在生存期内 都可以捕获makeStateMachine里面的 currentState 变量值 一直存在 //闭包可以超越自身的生命周期捕获外面的变量值

猜你在找的Swift相关文章