Skip to content

Instantly share code, notes, and snippets.

@smosko
Last active March 22, 2019 06:06
Show Gist options
  • Save smosko/1b405a16226e6eff2c1680c774addac3 to your computer and use it in GitHub Desktop.
Save smosko/1b405a16226e6eff2c1680c774addac3 to your computer and use it in GitHub Desktop.
Setup closures
/// make { ... }
func make<T>(_ setup: (T) -> Void) -> T where T: NSObject {
let instance = T()
setup(instance)
return instance
}
let label: UILabel = make {
$0.text = "Welcome"
$0.font = .systemFont(ofSize: 18)
$0.textColor = .blue
}
/// init().then { ... }
extension NSObjectProtocol where Self: NSObject {
func then(setup: (Self) -> Void) -> Self {
setup(self)
return self
}
}
lazy var button = UIButton(type: .system).then {
$0.setImage(UIImage(named: "Plus"), for: .normal)
$0.tintColor = .white
$0.addTarget(self, action: #selector(didTapPlusButton), for: .touchUpInside)
}
/// init { ... }
extension NSObjectProtocol where Self: NSObject {
init(_ setup: (Self) -> Void) {
self.init()
setup(self)
}
}
let label = UILabel {
$0.text = "Hello"
$0.font = .systemFont(ofSize: 18)
$0.textColor = .blue
}