当前位置:K88软件开发文章中心编程语言APP编程Swift01 → 文章内容

Swift 闭包

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-12 6:31:12

return runningTotal } return incrementor}let incrementByTen = makeIncrementor(forIncrement: 10)// 返回的值为10print(incrementByTen())// 返回的值为20print(incrementByTen())// 返回的值为30print(incrementByTen())以上程序执行输出结果为:102030闭包是引用类型上面的例子中,incrementByTen是常量,但是这些常量指向的闭包仍然可以增加其捕获的变量值。这是因为函数和闭包都是引用类型。无论您将函数/闭包赋值给一个常量还是变量,您实际上都是将常量/变量的值设置为对应函数/闭包的引用。 上面的例子中,incrementByTen指向闭包的引用是一个常量,而并非闭包内容本身。这也意味着如果您将闭包赋值给了两个不同的常量/变量,两个值都会指向同一个闭包:import Cocoafunc makeIncrementor(forIncrement amount: Int) -> () -> Int { var runningTotal = 0 func incrementor() -> Int { runningTotal += amount return runningTotal } return incrementor}let incrementByTen = makeIncrementor(forIncrement: 10)// 返回的值为10incrementByTen()// 返回的值为20incrementByTen()// 返回的值为30incrementByTen()// 返回的值为40incrementByTen()let alsoIncrementByTen = incrementByTen// 返回的值也为50print(alsoIncrementByTen())以上程序执行输出结果为:50

上一页  [1] [2] 


Swift 闭包