RSSAmplifier

samhuri.net · Oct 6, 2017

A nil-coalescing alternative for Swift

0
Sign in to vote or save

Sami Samhuri · samhuri.net

A nil-coalescing alternative for Swift

Swift compile times leave something to be desired and a common culprit is the affectionately-named nil-coalescing operator. A small extension to Optional can improve this without sacrificing a lot of readability.

extension Optional {
    func or(_ defaultValue: Wrapped) -> Wrapped {
        switch self {
        case .none: return defaultValue
        case let .some(value): return value
        }
    }
}

And you use it like so:

let dict: [String : String] = [:]
let maybeString = dict["not here"]
print("the string is: \(maybeString.or("default"))")
let otherString = dict["not here"].or("something else")

I’m sure someone else has come up with this already but I haven’t seen it yet.

(gist available here)

Read the original on samhuri.net

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.