XOR in Swift 5?
The ^
operator is defined for integer types but not for Bool
. You could add your own definition, but it's not strictly needed. The XOR operation on Bool
is the same as the !=
operation. Here's the truth tables for A XOR B
and A != B
:
A B A^B A!=BF F F FF T T TT F T TT T F F
So we could write your expression like this:
(card != nil) != (appointment.instructor == nil)
That is kind of hard to understand though. If the goal is to ensure that exactly one of the cases is true, I might write it like this for clarity:
[(card != nil), (appointment.instructor == nil)].filter({ $0 == true }).count == 1
The documentation clearly states that ^
is the bitwise XOR operator and since a Bool
is only a single bit, bitwise XOR is not defined on it. If you put correct parentheses on your expression, you get the correct error message:
(card != nil) ^ (appointment.instructor == nil)
Binary operator '^' cannot be applied to two 'Bool' operands
There's no XOR operator in Swift, so to do a XOR on two Bool
s, you need to define your own XOR function or operator.
infix operator ^^extension Bool { static func ^^(lhs:Bool, rhs:Bool) -> Bool { if (lhs && !rhs) || (!lhs && rhs) { return true } return false }}
Tests:
let trueValue:Bool? = truelet falseValue:Bool? = falselet nilValue:Bool? = nil(trueValue != nil) ^^ (nilValue != nil) // true(trueValue != nil) ^^ (falseValue != nil) // false(nilValue != nil) ^^ (nilValue != nil) // false