Configuration closure in Swift

Issue #2

When I was reading through Swinject, I found something interesting https://github.com/Swinject/Swinject/blob/master/Sources/Container.swift

1
2
3
4
public convenience init(parent: Container? = nil, registeringClosure: (Container) -> Void) {
self.init(parent: parent)
registeringClosure(self)
}

The init has a closure that makes configuration easy, much like a Builder pattern. So I think we can learn from that and make a Configurable protocol

1
2
3
4
5
6
7
8
9
10
protocol Configurable: class {}

extension Configurable {
func config(block: (Self) -> Void) -> Self {
block(self)
return self
}
}

extension NSObject : Configurable {}

With this, we can init some class with less hassle

1
2
3
4
let view = UIView().config {
$0.backgroundColor = .white
$0.layer.cornerRadius = 2
}

Comments