Search code examples
swiftxorswift5

XOR in Swift 5?


I'm trying to do an XOR operation in Swift 5. The documentation does not seem to mention explicitly doing it with two boolean values here:

https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html

Is this possible? It says to use the ^ operation but I get the error when trying:

 card != nil ^ appointment.instructor == nil

ERROR Adjacent operators are in non-associative precedence group 'ComparisonPrecedence'


Solution

  • 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)