Brane Dullet Brane Dullet - 6 months ago 16
iOS Question

Generics in Swift 2.0

I have been through the Swift tutorials on the Apple developer site, but I do not understand the concepts of Generics. Is anyone able to explain it in a simple way? For example:

func swapTwoValues<T>(inout a: T, inout b: T) {
let temporaryA = a
a = b
b = temporaryA
}

Answer

Without using generics in the example you gave, you'd have to overload swapTwoValues for every type you wanted to swap. For example:

func swapTwoValues(inout a: Int, inout b: Int) {
    let temp = a
    a = b
    b = temp
}

func swapTwoValues(inout a: String, inout b: String) {
    let temp = a
    a = b
    b = temp
} 

// Many more swapTwoValues functions...

The only thing that's different between the functions above is the type they accept; the code inside each is exactly the same. Therefore, it's better to write one generic function which can take any type.

It's important to note you can't substitute T with Any. There would be no guarantee a and b would be the same type - you couldn't swap an Int and a String, for example.

Comments