Chainable Methods and Builder Pattern in Swift

In one of my library (LayoutKit, it is not the LinkedIn one), you can layout a view with this code:

1
2
3
4
5
6
7
8
9
10
let containerView: UIView = UIView()
let box: UIView = UIView()
containerView.addSubview(box)

box.build { layout in
layout.centerX.equalTo().superView(.centerX)
layout.centerY.equalTo().superView(.centerY)
layout.width.equalTo().constant(30)
layout.height.equalTo().constant(30)
}

Builder Pattern

As you can see, build function is an extension in LayoutKit

1
2
3
4
5
6
7
8
9
10
11
import UIKit

public typealias LayoutContructor = ((LayoutBuilder) -> Void)

extension UIView {
public func build(layout: LayoutContructor!) {
let builder: LayoutBuilder = LayoutBuilder(view: self)
layout(builder)
builder.build()
}
}

The layout closure will pass a LayoutBuilder and this will expose to the library user to layout the view.

After that, the builder will build() all NSLayoutConstraint into the view.

Chainable Methods

This is one of the function that the builder can call

1
2
3
4
public func equalTo() -> Layout {
relationship = .equal
return self
}

The function will perform some actions and return self and it can call on other functions.

If the functions result is discardable, you can add @discardableResult before the function declaration.

1
2
3
4
5
@discardableResult
public func constant(_ layoutConstant: CGFloat) -> Layout {
constant = layoutConstant
return self
}
Share Comments