Skip to content

Instantly share code, notes, and snippets.

@pedrocid
Created February 9, 2016 19:27
Show Gist options
  • Save pedrocid/14e5684a3c6009acece7 to your computer and use it in GitHub Desktop.
Save pedrocid/14e5684a3c6009acece7 to your computer and use it in GitHub Desktop.
Example of Construction Builder in Swift
struct ObjectToConstruct {
let propertyOne: String?
let propertyTwo: Array<String>?
let propertyThree: Bool?
}
class ConstructBuilder {
private var propertyOne: String?
private var propertyTwo: Array<String>?
private var propertyThree: Bool?
func withPropertyOne(propertyOne: String) -> ConstructBuilder{
self.propertyOne = propertyOne
return self
}
func withPropertyTwo(propertyTwo: Array<String>) -> ConstructBuilder{
self.propertyTwo = propertyTwo
return self
}
func withPropertyThree(propertyThree: Bool) -> ConstructBuilder{
self.propertyThree = propertyThree
return self
}
func build() -> ObjectToConstruct {
return ObjectToConstruct(propertyOne: self.propertyOne ?? "", propertyTwo: self.propertyTwo ?? [], propertyThree: self.propertyThree ?? false)
}
}
//MARK: Use of the Construction Builder pattern
let objectWithAllProperties = ConstructBuilder().withPropertyOne("Hola")
.withPropertyTwo(["Hi","Allo"])
.withPropertyThree(true)
.build()
print(objectWithAllProperties)
let objectWithPropertyTwoByDefault = ConstructBuilder().withPropertyOne("Hola")
.withPropertyThree(true)
.build()
print(objectWithPropertyTwoByDefault)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment