Skip to content

Instantly share code, notes, and snippets.

@wh1pch81n
Last active September 3, 2016 16:43
Show Gist options
  • Save wh1pch81n/d79c0f917fa23475813cd11334fad95f to your computer and use it in GitHub Desktop.
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.
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