Last active
September 3, 2016 16:43
-
-
Save wh1pch81n/d79c0f917fa23475813cd11334fad95f to your computer and use it in GitHub Desktop.
Initialize an NSObject and set up its properties with a block. Useful for class variables.
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 | |
protocol Initializer {} | |
extension Initializer { | |
func with(bootStrap: (inout Self) -> ()) -> Self { | |
var s = self | |
bootStrap(&s) | |
return s | |
} | |
} | |
extension NSObject: Initializer {} | |
let L = UILabel().with { | |
$0.text = "freddie" | |
} | |
L.text // "freddie" | |
class Foo: Initializer { | |
var name = "" | |
} | |
let f = Foo().with { | |
$0.name = "bob" | |
} | |
f.name | |
struct Bar: Initializer { | |
var name = "" | |
} | |
let b = Bar().with { | |
$0.name = "Charlie" | |
} | |
b.name | |
// Also for sake of completion, an objective-c version | |
@interface NSObject (with) | |
- (instancetype)with:(void(^)(id))bootStrap; | |
@end | |
@implementation NSObject (with) | |
- (instancetype)with:(void(^)(id))bootStrap { | |
bootStrap(self); | |
return self; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment