Last active
November 7, 2018 12:43
-
-
Save pofat/c200525f3d6c32be71e323e82f478335 to your computer and use it in GitHub Desktop.
Better way to do initialization in Swift
This file contains hidden or 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
| // From https://github.com/devxoul/Then/blob/master/Sources/Then/Then.swift | |
| // It's easy to move them into your codebase | |
| import Foundation | |
| public protocol Then {} | |
| extension Then where Self: Any { | |
| /// Makes it available to set properties with closures just after initializing. | |
| /// | |
| /// let label = UILabel().then { | |
| /// $0.textAlignment = .Center | |
| /// $0.textColor = UIColor.blackColor() | |
| /// $0.text = "Hello, World!" | |
| /// } | |
| public func then(@noescape block: inout Self -> Void) -> Self { | |
| var copy = self | |
| block(©) | |
| return copy | |
| } | |
| /// Makes it available to set properties with closures just after initializing and copying the value types. | |
| /// | |
| /// let frame = CGRect().with { | |
| /// $0.origin.x = 10 | |
| /// $0.size.width = 100 | |
| /// } | |
| public func with(_ block: (inout Self) throws -> Void) rethrows -> Self { | |
| var copy = self | |
| try block(©) | |
| return copy | |
| } | |
| } | |
| extension Then where Self: AnyObject { | |
| /// Makes it available to set properties with closures just after initializing. | |
| /// | |
| /// let label = UILabel().then { | |
| /// $0.textAlignment = .Center | |
| /// $0.textColor = UIColor.blackColor() | |
| /// $0.text = "Hello, World!" | |
| /// } | |
| public func then(@noescape block: Self -> Void) -> Self { | |
| block(self) | |
| return self | |
| } | |
| } | |
| extension NSObject: Then {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment