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( { > } ) // 简写参数 隐式返回// reversed = ["Ewa","Alex"]reversed = names.sort { > } // 进一步简写// reversed = ["Ewa","Alex"]reversed = names.sort() { > } // 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(_:) 遍历numberslet 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 = 10print("incrementByTen = \(incrementByTen())") // incrementByTen = 20print("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"总结
以上是内存溢出为你收集整理的Swift 闭包Closures全部内容,希望文章能够帮你解决Swift 闭包Closures所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)