What is the type of the logical operators?

前端 未结 1 2013
离开以前
离开以前 2020-12-21 08:49

I want to use them as a parameter to a method of my Region struct:

private func combineWith(region: RegionProtocol, combine: (Bool, Bool) -&         


        
1条回答
  •  情歌与酒
    2020-12-21 09:23

    If you "cmd-click" on the word "Swift" in the statement

    import Swift
    

    in Xcode and search for || then you'll find that it is declared as

    func ||(lhs: T, rhs: @autoclosure () -> Bool) -> Bool
    

    The reason is the "short-circuiting" behaviour of the || operator: If the first operand is true, then the second operand must not be evaluated at all.

    So you have to declare the parameter as

    combine: (Bool, @autoclosure () -> Bool) -> Bool
    

    Example:

    func combineWith(a : Bool, b : Bool, combine: (Bool, @autoclosure () -> Bool) -> Bool) -> Bool {
        return combine(a, b)
    }
    
    let result = combineWith(false, true, ||)
    println(result)
    

    Note: I tested this with Xcode 6.1.1. The syntax for autoclosure parameters changed in Swift 1.2 (Xcode 6.3) and I haven't been able yet to translate the above code for Swift 1.2 (see also Rob's comments below).

    The only thing that I can offer at the moment are extremely ugly workarounds. You could wrap || into a closure that does not have autoclosure parameters:

    func combineWith(a : Bool, b : Bool, combine: (Bool, () -> Bool) -> Bool) -> Bool {
        return combine(a, { b })
    }
    
    let result = combineWith(false, true, { $0 || $1() } )
    

    Or you go without the short-circuiting behaviour:

    func combineWith(a : Bool, b : Bool, combine: (Bool, Bool) -> Bool) -> Bool {
        return combine(a, b)
    }
    
    let result = combineWith(false, true, { $0 || $1 } )
    

    0 讨论(0)
提交回复
热议问题