Is there any way to get the following working in Swift 3?
let button = UIButton().apply {
$0.setImage(UIImage(named: \"UserLocation\"), for: .normal
First of all lets define the HasApply protocol
protocol HasApply { }
and related extension
extension HasApply {
func apply(closure:(Self) -> ()) -> Self {
closure(self)
return self
}
}
Next let make NSObject conform to HasApply.
extension NSObject: HasApply { }
Let's test it
let button = UIButton().apply {
$0.titleLabel?.text = "Tap me"
}
print(button.titleLabel?.text) // Optional("Tap me")
I wouldn't use
NSObject(it's part of the Objective-C way of doing things and I assume it will be removed at some point in the future). I would prefer something likeUIViewinstead.
extension UIView: HasApply { }