加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift 闭包 由浅入深 优化

发布时间:2020-12-14 01:39:48 所属栏目:百科 来源:网络整理
导读://: Playground - noun: a place where people can playimport UIKit /////////////////////////////////////////// // //func sorted(isOrderedBefore:(T,T)-Bool) - [T]{ // //} let animals = [ "fish" , "cat" , "chicken" , "dog" ] //func isOrderedBe
//: 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 变量值 一直存在 //闭包可以超越自身的生命周期捕获外面的变量值

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读