I am trying to use an or statement ||. It is xcpde 7 using swift 2
or statement || not working with swift 2
The || or operator works fine in Swift 2, but both arguments have be of the type Bool (more precisely: implement the protocol BooleanValue). Do you have any example that doesn't work the way you expect?
I'm confused because they are all strings.
answer1 = "b"
answer2 = "a"
select1 = "a"
if select1 == answer1 || answer2 {
You'll have to write it like this:
if select1 == answer1 || select1 == answer2 {
If you really want that functionality, you can define it yourself. You could use "|", but since it is already taken for integers, I have used "||" in this Perl 6 inspired junction implementation.
protocol Junctionable : Hashable {}
struct OrJunction<T : Junctionable> {
let values : Set<T>
init(values: [T]) {
self.values = Set(values)
}
}
func ||<T : Junctionable>(lhs: T, rhs: T) -> OrJunction<T> {
return OrJunction<T>(values: [lhs, rhs])
}
infix operator ~~ {}
func ~~<T : Junctionable>(lhs: T, rhs: OrJunction<T>) -> Bool {
return rhs.values.contains(lhs)
}
extension String : Junctionable {}
let answer1 = "b"
let answer2 = "a"
let select1 = "a"
if select1 ~~ answer1 || answer2 {
print("select1 was among the values")
}