Skip to content

Instantly share code, notes, and snippets.

@kittinunf
Last active April 17, 2017 08:49
Show Gist options
  • Save kittinunf/58e30ed98326176650372c524964f234 to your computer and use it in GitHub Desktop.
Save kittinunf/58e30ed98326176650372c524964f234 to your computer and use it in GitHub Desktop.
public protocol Apply {}
extension Apply where Self: Any {
//let f = Foo().apply {
// $0.foo = 10
// $0.bar = "bar"
//}
public func apply(_ block: (inout Self) -> Void) -> Self {
var copy = self
block(&copy)
return copy
}
//UserDefaults.standard.do {
// $0.set("abc", forKey: "username")
// $0.set("abc@hotmail.com", forKey: "email")
// $0.synchronize()
//}
public func `do`(_ block: (Self) -> Void) {
block(self)
}
public func with<R>(_ receiver: Self, _ block: (Self) -> R) -> R {
return block(receiver)
}
}
struct Data {
var f1: String = ""
var f2: Int = 0
var f3: [Double] = []
}
extension Data : Apply {}
let d = Data().apply {
$0.f1 = "hello"
$0.f2 = 100
$0.f3 = [1.0,2.0,3.0]
}
print(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment