Created
February 9, 2016 19:27
-
-
Save pedrocid/14e5684a3c6009acece7 to your computer and use it in GitHub Desktop.
Example of Construction Builder in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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