Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Nil-rejection operator example
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
You can’t perform that action at this time.