Skip to content

Instantly share code, notes, and snippets.

@0xLeif
Created March 16, 2019 02:44
Show Gist options
  • Save 0xLeif/07951f5b45188b20e630d0928531e133 to your computer and use it in GitHub Desktop.
Save 0xLeif/07951f5b45188b20e630d0928531e133 to your computer and use it in GitHub Desktop.
Swift Builder
import Foundation
protocol Buildable {
init()
init(_ build: (inout Self) -> Self)
}
extension Buildable {
init(_ build: (inout Self) -> Self) {
var s = Self()
self = build(&s)
}
}
struct Pet {
var name: String
var age: Int
var owner: Person?
}
extension Pet: Buildable {
init() {
self = Pet(name: "N/A", age: 0, owner: nil)
}
}
struct Person {
var name: String
var age: Int
}
extension Person: Buildable {
init() {
self = Person(name: "N/A", age: 0)
}
}
var test = Person()
test.name = "Jabroni"
test.age = 34
let test2 = Person( { (person) -> Person in
person.name = "leif"
person.age = 23
return person
})
print(test2)
let petOne = Pet {
$0.name = "Doggo"
$0.age = 3
$0.owner = test2
return $0
}
print(petOne)
func print(person: Person) {
print("Printing: \(person)")
}
print(person: Person {
$0.name = "Nice"
return $0
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment