How to use Swift @autoclosure

后端 未结 6 1392
天命终不由人
天命终不由人 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:49

    This shows a useful case of @autoclosure https://airspeedvelocity.net/2014/06/28/extending-the-swift-language-is-cool-but-be-careful/

    Now, the conditional expression passed as the first parameter to until will be automatically wrapped up into a closure expression and can be called each time around the loop

    func until(pred: @auto_closure ()->L, block: ()->()) {
        while !pred() {
            block()
        }
    }
    
    // doSomething until condition becomes true
    until(condition) {
        doSomething()
    }
    

提交回复
热议问题