Last active
June 29, 2017 19:24
-
-
Save gravicle/3f40be5270d43ce9adef95ffbd404839 to your computer and use it in GitHub Desktop.
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 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