Skip to content

Instantly share code, notes, and snippets.

@janodev
Last active Jun 29, 2018
Embed
What would you like to do?
initialising idioms
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(&copy)
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
}
@bitwit
Copy link

bitwit commented Jun 29, 2018

👍 , nice thought experiments

The first one messed with my head at first but I got there. Reminds me of JavaScript self executing functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment