Brandon T. answered 06/25/19
Swift & iOS Expert
Hey, That's a great question.
Generics are useful when writing algorithms or functions that you want to run on any type of object or variable.
Let's use an example directly from Apple's Swift 5 documentation:
Let's say that you wanted to write a function that swaps two variable values with each other.
You have an "int a", and an "int b" and you want to swap them. You could have the following function to do so:
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
If you wanted to then use the same function to swap two Floats, or two Strings, you would have to write 2 more functions like so:
func swapTwoStrings(_ a: inout String, _ b: inout String) {
let temporaryA = a
a = b
b = temporaryA
}
func swapTwoDoubles(_ a: inout Double, _ b: inout Double) {
let temporaryA = a
a = b
b = temporaryA
}
All this extra work could be avoided if you wrote a single generic function to handle all primitive variable types like so:
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}
In the above ^ example: <T> is used as a placeholder type which will be replaced with the type given when the function is called. So you would be able to call this function with Strings, Ints, Floats, Doubles or even Bools.
This function can be called in the following way:
var someInt = 3
var anotherInt = 107
swapTwoValues(&someInt, &anotherInt)
// The generic function will call with a type of Int
var someString = "hello"
var anotherString = "world"
swapTwoValues(&someString, &anotherString)
// The generic function will call with a type of String
Note:: The "&" in front of the variables is a shorthand to pass inout parameters.
As you can see, generics are a powerful way to reduce the amount of code you need to write if you know a function or algorithm you are writing requires the need to run on multiple types of data without changing the fundamental implementation.
Hope this helped!