Series 7— Custom operators for better code readability.

Aron Balog
2 min readMar 30, 2018

--

Basic usage of custom operators is demonstrated in Series 6. But can we use them for something else? In this post we are gonna do little experiment.

This is the pure example how to use custom operators to improve code readability.

Our goal

let label = UILabel()
<- "Gimme some sugar." // text
<- 2 // number of lines
<- UIColor.black // text color
<- NSTextAlignment.right // text alignment
<- UIFont.preferredFont(forTextStyle: .largeTitle) // font
<- CGRect(x: 0, y: 200, width: 200, height: 100) // frame

Expected result

How to achieve this?

1. Declare custom operator <-

infix operator <-: AdditionPrecedence

2. Declare Configurable protocol:

protocol Configurable: class {}

3. Configurable default implementation for UIView:

extension Configurable where Self: UIView {
static func <-(left: Self, right: UIViewContentMode) -> Self {
left.contentMode = right

return left
}

static func <-(left: Self, right: CGRect) -> Self {
left.frame = right

return left
}
}

4. Configurable default implementation for UILabel:

extension Configurable where Self: UILabel {
static func <-(left: Self, right: String) -> Self {
left.text = right

return left
}

static func <-(left: Self, right: UIColor) -> Self {
left.textColor = right

return left
}

static func <-(left: Self, right: NSTextAlignment) -> Self {
left.textAlignment = right

return left
}

static func <-(left: Self, right: UIFont) -> Self {
left.font = right

return left
}

static func <-(left: Self, right: Int) -> Self {
left.numberOfLines = right

return left
}
}

5. Conform UIView to Configurable:

extension UIView: Configurable {}

That’s it!

It kinda look like a new syntax, doesn’t it? :)

let label = UILabel()
<- "Gimme some sugar." // text
<- 2 // number of lines
<- UIColor.black // text color
<- NSTextAlignment.right // text alignment
<- UIFont.preferredFont(forTextStyle: .largeTitle) // font
<- CGRect(x: 0, y: 200, width: 200, height: 100) // frame

--

--

Aron Balog

Unstoppable coder, passionate about software architecture, primarily focused on iOS development. https://github.com/aronbalog | https://twitter.com/Aron_Balog