Skip to content

Instantly share code, notes, and snippets.

@miguelbassila
Created April 19, 2016 01:19
Show Gist options
  • Save miguelbassila/420253b2d9ec0012ac4c36ca4fddc934 to your computer and use it in GitHub Desktop.
Save miguelbassila/420253b2d9ec0012ac4c36ca4fddc934 to your computer and use it in GitHub Desktop.
Design Pattern: Builder
class PersonBuilder {
private final var name: String
private final var age: String?
private final var gender: String?
init(name: String) {
self.name = name
}
func with(age age: String) -> Self {
self.age = age
return self
}
func with(gender gender: String) -> Self {
self.gender = gender
return self
}
func build() -> Person {
return Person(builder: self)
}
}
struct Person {
let name: String
let age: String?
let gender: String?
init(builder: PersonBuilder) {
name = builder.name
age = builder.age
gender = builder.gender
}
}
let cegela = PersonBuilder(name: "Cegela").with(age: "20").with(gender: "M").build()
let mucuge = PersonBuilder(name: "Mucuge").with(gender: "M").with(age: "25").build()
@aterribili
Copy link

aterribili commented Apr 21, 2016

Look this example of Builder using closure: https://github.com/elo7/Nayau/blob/master/nayau/Message.swift

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment