How To XOR Booleans In Swift

By Eddy Chung

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, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts