Method chaining in Swift

Dzung Nguyen
Jul 23, 2017 · 2 min read

Have you ever using Alamofire library when develop an iOS Swift app? You may get curious in the way they call method in this library, for example:

They call methods step by step by using dot operator. This seems familiar to the way each class call its method or variable. Yes, they are exactly the same. After each method executes, it returns an instance of that object, therefore we can call the next method by using dot operator. So how to do that?

Let’s start with the traditional way of calling methods

Here we have a class Name. Each Name has firstName and lastName, together they form fullName. After creating fullName by concatenating firstName and lastName, we need to remove redundant spaces in the name. To do those tasks, we need to call method join() first, then go to removeSpace(), and finally print the result. You can see that this is really take time to type those methods since we need to type name.doSomething() for every action. So how to omit this?

Each method now will have a return type Self. At the end of each method, method will return its instance. On top of each method has a keyword discardableResult to avoid warning of unused result. Hence, after calling a method, we can call the next method by using the dot operator. This approach is very clean, short and easy.

Another advantage of this approach is to avoid missing parameters in a method where you might have a lot of closure to pass in but you may don’t have to use it all time. For example in the case of downloading file with Alamofire, you may need to receive the response, but you don’t need to know the progress. No matter you need or not, in the method implementation, progress block always be there. Using method chaining will help to resolve this problem.

In this example, class A requires 2 closures to pass in the function doSomething. Whenever you call doSomething, you’ll need to provide both closure or else there will be compile error.

However, with method chaining, we only need to call one of 2, closure1 or closure2 base on the need of the task.

As you see, method chaining improve the readability of our code, but in some case it will become tricky to debug and there may be some workarounds between the method will fail. So be careful using it.

Dzung Nguyen

Written by

I’m a full-time dreamer, and also a developer. My Git: https://github.com/dzungnguyen1993

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade