Search code examples
iosswiftswapxor

Generic XOR Swap in Swift


Today I was reading about XOR Swaps, and figured I would try to implement a function in Swift that would do this. I successfully wrote a non-generic version of this function:

import UIKit

func xorSwap (inout x: Int, inout y: Int) {
    if x != y {
        x ^= y
        y ^= x
        x ^= y
    }
}


var a = 10
var b = 20

xorSwap(&a, &b)

println(a) //=> 20
println(b) //=> 10

I then tried writing a generic version of this, but the compiler complained that 'T is not identical to Bool'. I'm assuming there's another protocol I need to declare conformance to, but I'm not sure what that is. Here's the attempt at a generic version:

import UIKit

func xorSwap<T: Equatable> (inout x: T, inout y: T) {
    if x != y {
        x ^= y
        y ^= x
        x ^= y
    }
}


var a = 10
var b = 20

xorSwap(&a, &b)

println(a)
println(b)  

Does anyone have a better understanding of this and can help me fill the gaps in my understanding? Thanks.


Solution

  • You can use built-in BitwiseOperationsType

    func xorSwap<T: protocol<BitwiseOperationsType, Equatable>> (inout x: T, inout y: T) {
        if x != y {
            x ^= y
            y ^= x
            x ^= y
        }
    }
    
    var a = 10
    var b = 20
    
    xorSwap(&a, &b)
    
    println(a) // -> 20
    println(b) // -> 10
    

    var a = NSStringCompareOptions.CaseInsensitiveSearch
    var b = NSStringCompareOptions.BackwardsSearch
    
    xorSwap(&a, &b)
    
    a == .BackwardsSearch // -> true
    b == .CaseInsensitiveSearch // -> true