Using generic functions

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 self.saveModel(user, on: app)

See how such a function could be very useful when doing operations on a number of types that are all conforming to the same superclass or protocol?

In this simple example, we are not saving much, but in projects where you might want to perform a good number of transformations before saving a model, generic functions can be life-saving.

Now we have looked at the perks of the Swift language specifically. Extensions, protocols, and generic functions should now be part of your portfolio when writing server-side Swift applications! Let's now look at when to be abstract and when to be concrete in your implementations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.11.230