(Swift 3)
var a: Int = 15
var b: Int = 12
func swap( a: inout Int, b: inout Int){
(a, b) = (b, a)
}
print("a is \(a) ") //15
swap(a: &a, b: &b)
print("a is \(a) ") //12
So far, so good. I really like that this is doing away with the extra variable in many implementations: temp = a, a = b, b = temp. Making it generic wasn’t quite as intuitive for me: ‘T’ must be declared in the function name before it can be used.
func swap( a: inout T, b: inout T){
(a, b) = (b, a)
}
Of course, you can just use Swift’s inbuilt Swap function, but I felt that both the tuple trick and the generic usage were worth writing down.
Nov 27 2016
Basic (generic) swap function
(Swift 3)
var a: Int = 15
var b: Int = 12
func swap( a: inout Int, b: inout Int){
(a, b) = (b, a)
}
print("a is \(a) ") //15
swap(a: &a, b: &b)
print("a is \(a) ") //12
So far, so good. I really like that this is doing away with the extra variable in many implementations: temp = a, a = b, b = temp. Making it generic wasn’t quite as intuitive for me: ‘T’ must be declared in the function name before it can be used.
func swap( a: inout T, b: inout T){
(a, b) = (b, a)
}
Of course, you can just use Swift’s inbuilt Swap function, but I felt that both the tuple trick and the generic usage were worth writing down.
By Extelligent Cocoa • Wiki • • Tags: generics