Skip to content

Instantly share code, notes, and snippets.

@janodev
Last active June 29, 2018 16:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janodev/f40e9380b46c6d06df77f8c4e4681a18 to your computer and use it in GitHub Desktop.
Save janodev/f40e9380b46c6d06df77f8c4e4681a18 to your computer and use it in GitHub Desktop.
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