swift 闭包 由浅入深 优化

//: Playground - noun: a place where people can play

import UIKit
 /////////////////////////////////////////// // //func sorted(isOrderedBefore:(T,T)->Bool) -> [T]{ //  //}

let  animals = ["fish","cat","chicken","dog"]
 //func isOrderedBefore(one : String,two: String) -> Bool //{ // return one < two //} // //let sortedString = animals.sort(isOrderedBefore)
 // 与排序 小于号 ,传递核心代码

let sortedString = animals.sort({(one: String,two: String) -> Bool  in
    return one < two

})
 // 在sort 函数里面传递了参数 而参数又是一个函数 ,这个函数就叫做闭包
 // 闭包 没有完整的函数声明 有参数列表 one: String,two: String // in关键字后面是闭包的实现代码 
 // 编译器可以断言出参数的类型
let sortedString2 = animals.sort({(one,two) -> Bool  in
    return one < two

})
 // -> Bool 返回值信息也可以 删除掉 这个信息可以再sort的声明中得到< sort 声明>
let sortedString3 = animals.sort({(one,two)  in
    return one < two

})

 // 没有返回值类型->bool声明以后 ()也可以去除

let sortedString4 = animals.sort({one,two   in
    return one < two

})
 // 可以省略执行代码的return语句 编译器已经断言出来返回值是bool 类型  //所执行代码一行,删除return 语句

let sortedString5 = animals.sort({one,two   in
     one < two
})
 //接下来我们还可以省略参数 // one two 没有意义 用参数本地常量进行代替

let sortedString6 = animals.sort({$0 < $1})
 //如果传递的闭包是方法或者函数的最后一个参数, 可以将闭包放到闭包的外面 //称为结尾闭包

let sortedString7 = animals.sort(){$0 < $1}
print(sortedString7)
 // 还可以移除没有参数的括号
let sortedString8 = animals.sort{$0 < $1}
print(sortedString8)
 //把花括号替换为小括号 只写一个 < 闭包神奇之处
let sortedString9 = animals.sort(>)
print(sortedString9) //---------------------------------------------- //闭包还可以捕获 上下文中常量或者变量的数值 //甚至原始环境销毁也可以使用

typealias stateMachineType = () ->Int

func makeStateMachine(maxState: Int) -> stateMachineType{

    var currentState: Int = 0

    return{
        currentState++
        if currentState > maxState{
            currentState = 0
        }
        return currentState
    }
}

let tt = makeStateMachine(2)

print(tt())

print(tt())

print(tt())

print(tt())

print(tt())

 // 不管makeStateMachine 是否在生存期内 都可以捕获makeStateMachine里面的 currentState 变量值 一直存在 //闭包可以超越自身的生命周期捕获外面的变量值

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...