Wednesday 15 July 2015

ios - Generic XOR Swap in Swift -



ios - Generic XOR Swap in Swift -

today reading xor swaps, , figured seek implement function in swift this. wrote non-generic version of function:

import uikit func xorswap (inout x: int, inout y: int) { if x != y { x ^= y y ^= x x ^= y } } var = 10 var b = 20 xorswap(&a, &b) println(a) //=> 20 println(b) //=> 10

i tried writing generic version of this, compiler complained 't not identical bool'. i'm assuming there's protocol need declare conformance to, i'm not sure is. here's effort @ generic version:

import uikit func xorswap<t: equatable> (inout x: t, inout y: t) { if x != y { x ^= y y ^= x x ^= y } } var = 10 var b = 20 xorswap(&a, &b) println(a) println(b)

does have improve understanding of , can help me fill gaps in understanding? thanks.

you can utilize 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 = 10 var b = 20 xorswap(&a, &b) println(a) // -> 20 println(b) // -> 10 var = nsstringcompareoptions.caseinsensitivesearch var b = nsstringcompareoptions.backwardssearch xorswap(&a, &b) == .backwardssearch // -> true b == .caseinsensitivesearch // -> true

ios swift swap xor

No comments:

Post a Comment