Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 380
Kiran P Nair Avatar asked Jun 23 '15 08:06

Kiran P Nair


1 Answers

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.

like image 96
ABakerSmith Avatar answered Sep 26 '22 03:09

ABakerSmith