March 2020
Intermediate to advanced
392 pages
10h 10m
English
A generic function is one that can take multiple types and work with them equally. Especially in server applications, where you deal with a lot of data, this becomes very handy. Instead of writing a function for each type of information, you can write it once and use it for every type.
Let's look at an example:
function saveModel<T:Model>(_ model: T, on app: Application) -> EventLoopFuture<T> { return model.save(on: app).transform(to: model)}
You can see that the function is using a generic type T that we call model in the signature of the function. We are also defining that this type has to implement Model.
Now, whenever we want to save a class that conforms to Model, we can do so as follows:
let user = User()return ...
Read now
Unlock full access