Swift 闭包Closures

前端之家收集整理的这篇文章主要介绍了Swift 闭包Closures前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
什么是Closures?
Closures是自包含的代码块,在代码中使用或是作为参数传值,和OC中的blocks类似.
Swift中闭包的优势
1.根据上下文推断参数和返回值类型
2.隐式返回(可以省略return)
3.简化参数(如$0,$1;从0开始表示第n个参数)
4.Trailing闭包表达式

闭包表达式形式


具体实例:

// 使用函数
let names = ["Chris","Alex","Ewa","Barry","Daniella"]
func backwards(s1: String,_ s2: String) -> Bool {
    return s1 > s2
}
var reversed = names.sort(backwards)
// reversed = ["Ewa","Daniella","Chris","Alex"]
// 使用闭包
reversed = names.sort({ (s1: String,s2: String) -> Bool in
    return s1 > s2
})
// reversed = ["Ewa","Alex"]
reversed = names.sort( { s1,s2 in return s1 > s2 } )
// reversed = ["Ewa","Alex"]
reversed = names.sort( { $0 > $1 } ) // 简写参数 隐式返回
// reversed = ["Ewa","Alex"]
reversed = names.sort { $0 > $1 }    // 进一步简写
// reversed = ["Ewa","Alex"]
reversed = names.sort() { $0 > $1 }  // Trailing闭包
// reversed = ["Ewa","Alex"]
reversed = names.sort(>)             // Operator Functions Swift中定义了一个>作为函数,并返回一个bool类型的数据
// reversed = ["Ewa","Alex"]

let digitNames = [
    0: "Zero",1: "One",2: "Two",3: "Three",4: "Four",5: "Five",6: "Six",7: "Seven",8: "Eight",9: "Nine"
]
let numbers = [16,58,510]
//  map(_:) 遍历numbers
let strings = numbers.map {
    (number) -> String in
    var number = number
    var output = ""
    while number > 0 {
        output = digitNames[number % 10]! + output  // 先取出个位
        number /= 10                                // 取出十位
    }
    print("output = \(output)")  // 依次打印:OneSix,FiveEight,FiveOneZero
    return output
}
// 值捕获
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incrementer
}
// 引用闭包
let incrementByTen = makeIncrementer(forIncrement: 10)
print("incrementByTen = \(incrementByTen())") // incrementByTen = 10
print("incrementByTen = \(incrementByTen())") // incrementByTen = 20
print("incrementByTen = \(incrementByTen())") // incrementByTen = 30

// Nonescaping 闭包
func someFunctionWithNonescapingClosure(@noescape closure: () -> Void) {
    closure()
}
var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: () -> Void) {
    completionHandlers.append(completionHandler)
}
class SomeClass {
    var x = 10
    func doSomething() {
        someFunctionWithEscapingClosure { self.x = 100 }
        someFunctionWithNonescapingClosure { x = 200 }
    }
}

let instance = SomeClass()
instance.doSomething()
print(instance.x)
// Prints "200"

completionHandlers.first?()
print(instance.x)
// Prints "100"
原文链接:https://www.f2er.com/swift/324668.html

猜你在找的Swift相关文章