Last active
February 8, 2017 21:48
-
-
Save jnewc/304bdd2d330131ddb8a1e615ee560d1d to your computer and use it in GitHub Desktop.
Nil-rejection operator example
This file contains 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
infix operator !! : NilCoalescingPrecedence | |
func !!<UnwrappedType: Any, ErrorType: Error>(lhs: Optional<UnwrappedType>, rhs: ErrorType) throws -> UnwrappedType { | |
guard let unwrappedValue = lhs else { | |
throw rhs | |
} | |
return unwrappedValue | |
} | |
/****************************************************************************************************/ | |
/* Dictionary access example */ | |
/****************************************************************************************************/ | |
enum Errors: Error { | |
case keyNotFound(key: String) | |
case oneOfKeysNotFound(keys: [String]) | |
} | |
let sampleDictionary: [String: Int] = [ | |
"First": 0, | |
"Second": 1, | |
"Fourth": 2, | |
"Fifth": 3 | |
] | |
// Nil-rejection on a single item | |
do { | |
let first = try sampleDictionary["First"] !! Errors.keyNotFound(key: "First") | |
let second = try sampleDictionary["Second"] !! Errors.keyNotFound(key: "Second") | |
let third = try sampleDictionary["Third"] !! Errors.keyNotFound(key: "Third") | |
let fourth = try sampleDictionary["Fourth"] !! Errors.keyNotFound(key: "Fourth") | |
} catch let e { | |
print(e) | |
} | |
// Nil-rejection with nil-coalescence | |
do { | |
let first = | |
try sampleDictionary["First"] ?? | |
sampleDictionary["Second"] !! | |
Errors.oneOfKeysNotFound(keys: ["First", "Second"]) | |
try sampleDictionary["Third"] ?? | |
sampleDictionary["Second"] !! | |
Errors.oneOfKeysNotFound(keys: ["Third", "Second"]) | |
try sampleDictionary["Third"] ?? | |
sampleDictionary["Sixth"] !! | |
Errors.oneOfKeysNotFound(keys: ["Third", "Sixth"]) | |
try sampleDictionary["Third"] ?? | |
sampleDictionary["Sixth"] ?? | |
sampleDictionary["Seventh"] !! | |
Errors.oneOfKeysNotFound(keys: ["Third", "Sixth", "Seventh"]) | |
} catch let e { | |
print(e) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment