Generic methods in Swift
Forums:
func swap<T>(inout a: T, inout _ b: T) {
let tmp = a
a = b
b = tmp
}
var n1 = 5
var n2 = 7
swap(&n1, &n2)
//n1 is 7 and n2 is 5
var s1 = "cat"
var s2 = "dog"
swap(&s1, &s2)
//s1 is "dog" and s2 is "cat"
- Log in to post comments