In previous articles, whenever we used a variable, we had to define its type (or it was inferred). So in case we need to declare multiple methods with similar behavior for different types of parameters, we had to create one for each type. Letโs take a look at an example.
func show(element: Int) {
print("My variable: \(element)")
}
func show(element: String) {
print("My variable: \(element)")
}
func show(element: Bool) {
print("My variable: \(element)")
}
Generics in methods
We can replace these 3 methods with a single one that uses a generic type, which we will name T
.
func show<T>(element: T) {
print("My variable: \(element)")
}
show(element: "Hello")
show(element: 23)
show(element: true)
Type constraints
We can set constraints to our generic type. For example, if we want to perform a mathematical operation, our generic parameter should be Numeric
. To achieve this, we can specify that the type must adopt that protocol.
func cube<T: Numeric>(number: T) -> T {
return number * number * number
}
let myNumber: Int = 3
let result = cube(number: myNumber)
Inferring the type
When using Generics, the type needs to be inferred in some way. Usually this is done automatically depending on the parameters we use, but in case you have an error just define a type of any variable the generic type is used like we did in the example above, or in the result:
let result: Double = cube(number: 2)
Generic Classes
We can use a generic type as a property in an object, we just need to define it alongside the object name and use it at least once.
class MyGroup<T> {
let items: [T]
init(items: [T]) {
self.items = items
}
}
Since in this case the generic is used in the init
, the type will be inferred, so we can use this class like any other.
struct Person {
let name: String
}
let personsGroup = MyGroup(
items: [
Person(name: "Pablo"),
Person(name: "Andrea")
]
)
let numbersGroup = MyGroup(items: [1, 2, 5, 4, 23])
If the type cannot be inferred, as in the following example where the init
doesnโt include any T
parameter, we can define it like this.
class MyGroup<T> {
var items: [T] = []
init() {
}
func add(item: T) {
items.append(item)
}
}
struct Person {
let name: String
}
let personsGroup = MyGroup<Person>()
personsGroup.add(item: Person(name: "Pablo"))
let numbersGroup = MyGroup<Int>()
numbersGroup.add(item: 3)
Be the first to comment