Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swift - What is the type of the logical operators?

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

private func combineWith(region: RegionProtocol, combine: (Bool, Bool) -> Bool) -> Region {
    return Region() {point in
        combine(self.contains(point), region.contains(point))
    }
}

But apparently, (Bool, Bool) -> Bool) is not what && or || are. If you know, please let me know how you found out.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ||<T : BooleanType>(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 } )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...