Skip to content

Instantly share code, notes, and snippets.

@gravicle
Last active June 29, 2017 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gravicle/3f40be5270d43ce9adef95ffbd404839 to your computer and use it in GitHub Desktop.
Save gravicle/3f40be5270d43ce9adef95ffbd404839 to your computer and use it in GitHub Desktop.
struct Person {
let firstName: String
let lastName: String
let ethnicity: String?
}
// Using throwable optional unwrapping
extension Person {
init(firstName: String?, lastName: String?, ethnicity: String?) throws {
self.firstName = try firstName.unwrapped(withName: "firstName")
self.lastName = try lastName.unwrapped(withName: "lastName")
self.ethnicity = ethnicity
}
}
// Using regular optional unwrapping
extension Person {
init(firstName: String?, lastName: String?) throws {
guard let fName = firstName else {
throw MissingValueError(valueName: "fisrtName")
}
guard let lName = lastName else {
throw MissingValueError(valueName: "lastName")
}
self.firstName = fName
self.lastName = lName
self.ethnicity = nil // just so the above init is distinct from this one
}
}
// ----------
struct MissingValueError: Error, CustomStringConvertible {
let valueName: String
var description: String {
return "Missing value for \(valueName)"
}
}
extension Optional {
func unwrapped(withName name: String? = nil) throws -> Wrapped {
switch self {
case .some(let value):
return value
case .none:
let name = name ?? String(describing: Wrapped.self)
throw MissingValueError(valueName: name)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment