What is trailing closure syntax in Swift?

前端 未结 4 1684
执笔经年
执笔经年 2020-12-06 23:12

Swift\'s documentation on closures states:

Swift’s closure expressions have a clean, clear style, with optimizations that encourage brief, clutter-fre

4条回答
  •  隐瞒了意图╮
    2020-12-06 23:33

    A trailing closure is written after the function call’s parentheses, even though it is still an argument to the function. When you use the trailing closure syntax, you don’t write the argument label for the closure as part of the function call.

    func doSomething(number:Int, onSuccess closure:(Int)->Void) {
    
        closure(number * number * number)
    
    }
    
    doSomething(number: 100) { (numberCube) in
    
        print(numberCube) // prints  1000000
    
    }
    

    The argument label onSuccess is not there in the function call. Even though the closure is included in the function parameters list, swift will take it out of the parameter block to make the code more readable.

提交回复
热议问题