Method Chaining in Swift Using Self Returning Functions | by Tom Manuel

Use declarative programming in UIKit

photo by Matthew Lancaster Feather unsplash

Wikipedia Defines method chaining:

method chainingalso known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together into a single statement without the need for variables to store intermediate results.

Chances are, most of us have already used method chaining at some point or the other.
But here I want to talk about a special type of these object returning functions, that is returns Self,

Let’s dive in using an example.

Simple declarative UI creation using UIKit

In the above snippet, an object of UIButton is created, which is used to set button attributes like background/title color, button title text, etc. Finally, a target action is added to the same.

now let’s see how Self Returning functions can help here.

UIButton extension with self returning function

the above code snippet is a UIButton Extension with some functions. Each of these function bodies basically sets one or more button properties. If you notice, all the functions here have two things in common:

  1. they are all marked with @discardableResult Speciality This is to suppress the compiler warning because in most cases we will not explicitly store/use the return value of this function. You’ll see it in a while.
  2. they all have a return type Self, This is what lets us chain function calls.

So let’s put these functions to use.

Declarative UI creation using chained methods in UIKit

Every time we edit a Button attribute using the functions declared above, we get a Button object as the return value, which can be used to invoke the new function.

Furthermore, in most cases, we don’t even need to declare a variable to store it (unless, of course, you want to edit the button attributes at some later point).

For example, we are adding this button to a StackView, you can just define it inside arrangedSubviews array, as shown below.

The UIKit classes combined with these beautiful and simple extensions make declarative UI creation a seamless experience.

This type of method chaining is not limited to UIKit classes and can be combined with any class type. One such widely used example is the Alamofire Request API.

Leave a Reply