Last active
March 22, 2019 06:06
-
-
Save smosko/1b405a16226e6eff2c1680c774addac3 to your computer and use it in GitHub Desktop.
Setup closures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://itnext.io/refactoring-in-swift-setup-closures-d06b896c412c
https://www.reddit.com/r/swift/comments/9efxuj/refactoring_in_swift_setup_closures/
https://medium.com/the-traveled-ios-developers-guide/swift-initialization-with-closures-5ea177f65a5
https://mackarous.com/dev/2019/1/23/a-better-syntax-for-configurable-initializations