Skip to content

Instantly share code, notes, and snippets.

@muuhoffman
Last active August 28, 2017 18:50
Show Gist options
  • Save muuhoffman/517036683dc1841612d4b2e209651f7e to your computer and use it in GitHub Desktop.
Save muuhoffman/517036683dc1841612d4b2e209651f7e to your computer and use it in GitHub Desktop.
The common way of using the Builder Pattern in Swift
struct UserSignUp {
var firstName: String
var lastName: String?
var username: String
var password: String
class Builder {
var firstName: String?
var lastName: String?
var username: String?
var password: String?
var confirmPassword: String?
func set(firstName: String) -> Builder {
self.firstName = firstName
return self
}
func set(lastName: String) -> Builder {
self.lastName = lastName
return self
}
func set(username: String) -> Builder {
self.username = username
return self
}
func set(password: String) -> Builder {
self.password = password
return self
}
func set(confirmPassword: String) -> Builder {
self.confirmPassword = confirmPassword
return self
}
func build() -> UserSignUp? {
guard let firstName = firstName, !firstName.isEmpty else {
return nil
}
// last name not required, so don't unwrap
guard lastName?.isEmpty ?? true else {
return nil
}
guard let username = username, !username.isEmpty else {
return nil
}
guard let password = password, password.characters.count >= 4 else {
return nil
}
guard let confirmPassword = confirmPassword, confirmPassword == password else {
return nil
}
return UserSignUp(firstName: firstName, lastName: lastName, username: username, password: password)
}
}
}
// USAGE
let user: User? = User.Builder()
.set(firstName: "Matt")
.set(lastName: "Hoffman")
.set(username: "muuhoffman")
.set(password: "foo")
.set(confirmPassword: "foo")
.build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment