Swift removed the XOR (^) for Booleans many versions ago.
For most cases, using the !=
operator will achieve a XOR.
Take a look at the truth table for XOR
:
bool1 | bool2 | result |
---|---|---|
true | true | false |
true | false | true |
false | false | false |
false | true | true |
This is the same as the truth table for not equal to !=
:
bool1 | bool2 | result |
---|---|---|
true | true | false |
true | false | true |
false | false | false |
false | true | true |
Thus, you can use a !=
every time you want to use an XOR ^
.
If you really want to use the ^
operator in Swift, you can write a bool extension like so:
import UIKit
extension Bool {
static func ^ (left: Bool, right: Bool) -> Bool {
return left != right
}
}
let a = true
let b = false
print (a^b)
This will allow you to use the ^
operator as an XOR.
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.