Last active
June 29, 2018 16:17
-
-
Save janodev/f40e9380b46c6d06df77f8c4e4681a18 to your computer and use it in GitHub Desktop.
initialising idioms
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
import UIKit | |
// this one doesn’t require a helper function | |
var label: UILabel = { | |
$0.backgroundColor = .blue | |
$0.text = "This is a playground" | |
$0.textColor = .white | |
$0.textAlignment = .center | |
return $0 | |
}(UILabel(frame: .init(x: 0, y: 0, width: 100, height: 100))) | |
// if you rather write the function at the beginning... | |
func configure<T>(_ object: T, changes: (_ object: T) -> Void) -> T { | |
changes(object) | |
return object | |
} | |
var label2 = configure(UILabel(frame: .init(x: 0, y: 0, width: 100, height: 100))) { | |
$0.backgroundColor = .blue | |
$0.text = "This is a playground" | |
$0.textColor = .white | |
$0.textAlignment = .center | |
} | |
// another way, because why not | |
extension Sugar where Self: Any { | |
func then(_ block: (inout Self) -> Void) -> Self { | |
var copy = self | |
block(©) | |
return copy | |
} | |
} | |
extension NSObject: Sugar {} | |
var label: UILabel = UILabel(frame: .init(x: 0, y: 0, width: 100, height: 100).then { | |
$0.backgroundColor = .blue | |
$0.text = "This is a playground" | |
$0.textColor = .white | |
$0.textAlignment = .center | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍 , nice thought experiments
The first one messed with my head at first but I got there. Reminds me of JavaScript self executing functions