How To XOR Booleans In Swift

Swift removed the XOR (^) for Booleans many versions ago.

How To XOR in Swift

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 ^.

XOR Swift Extension

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.

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts