funcsomeFunctionThatTakesAClosure(closure: () -> ()) { // function body goes here }
// here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure({ // closure's body goes here })
// here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() { // trailing closure's body goes here }
值捕获
1 2 3 4 5 6 7 8
funcmakeIncrementer(forIncrementamount: Int) -> () -> Int { var runningTotal =0 funcincrementer() -> Int { runningTotal += amount return runningTotal } return incrementer }
闭包是引用类型
1 2 3 4 5 6 7 8 9 10 11 12 13
let incrementByTen = makeIncrementer(forIncrement: 10) incrementByTen() // returns a value of 10 incrementByTen() // returns a value of 20 incrementByTen() // returns a value of 30 incrementByTen() // returns a value of 40
let alsoIncrementByTen = incrementByTen alsoIncrementByTen() // returns a value of 50