Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XOR in Swift 5?

Tags:

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'

like image 447
Zack117 Avatar asked Apr 02 '19 15:04

Zack117


People also ask

What is XOR in Swift?

The bitwise XOR operator, or “exclusive OR operator” ( ^ ), compares the bits of two numbers.

What is XOR used for?

(eXclusive OR) A Boolean logic operation that is widely used in cryptography as well as in generating parity bits for error checking and fault tolerance. XOR compares two input bits and generates one output bit. The logic is simple. If the bits are the same, the result is 0.

What is the XOR value?

XOR is defined as exclusive or for two integers say a and b. To find XOR, we will first find the binary representation of both a and b. Lets do this also by example. Suppose a = 7 and b = 10.


1 Answers

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)
like image 123
Josh Homann Avatar answered Oct 09 '22 02:10

Josh Homann