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 变量值 一直存在
//闭包可以超越自身的生命周期捕获外面的变量值



转载于:https://www.cnblogs.com/ToBeFrank/p/4985300.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值