How to use Swift @autoclosure

后端 未结 6 1388
天命终不由人
天命终不由人 2020-12-02 04:44

I noticed when writing an assert in Swift that the first value is typed as

@autoclosure() -> Bool

with an overloaded method

6条回答
  •  再見小時候
    2020-12-02 04:59

    Consider a function that takes one argument, a simple closure that takes no argument:

    func f(pred: () -> Bool) {
        if pred() {
            print("It's true")
        }
    }
    

    To call this function, we have to pass in a closure

    f(pred: {2 > 1})
    // "It's true"
    

    If we omit the braces, we are passing in an expression and that's an error:

    f(pred: 2 > 1)
    // error: '>' produces 'Bool', not the expected contextual result type '() -> Bool'
    

    @autoclosure creates an automatic closure around the expression. So when the caller writes an expression like 2 > 1, it's automatically wrapped into a closure to become {2 > 1} before it is passed to f. So if we apply this to the function f:

    func f(pred: @autoclosure () -> Bool) {
        if pred() {
            print("It's true")
        }
    }
    
    f(pred: 2 > 1)
    // It's true
    

    So it works with just an expression without the need to wrap it in a closure.

提交回复
热议问题