XOR in Swift 5?

You need to define ^ for Bool since it only exists for Ints. See the apple documentation here.

Example:

import UIKit
import PlaygroundSupport

extension Bool {
    static func ^ (left: Bool, right: Bool) -> Bool {
        return left != right
    }
}

let a = true
let b = false
print (a^b)

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!=B
F F  F   F
F T  T   T
T F  T   T
T 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 Bools, 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? = true
let falseValue:Bool? = false
let nilValue:Bool? = nil

(trueValue != nil) ^^ (nilValue != nil) // true
(trueValue != nil) ^^ (falseValue != nil) // false
(nilValue != nil) ^^ (nilValue != nil) // false

Tags:

Xor

Swift

Swift5