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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With