Exhaustive, safe, non-optional Dictionary lookups

Another little tweak in response to a Swift Evolution thread:

public extension Dictionary {
    public subscript(key: Key, default fallback: Value) -> Value {
        return self[key] ?? fallback

Always returns an unwrapped value. You supply a fallback.

values[self, default: "?"]

If you omit the external default keyword, it looks like this instead:

values[self, "?"]

One Comment

  • Interesting proposition. I love seeing your thoughts on this great language! I wonder, does this solution bring much value over using the nil coalescing operator? I like the idea of mixing in a default parameter argument, but looks funky to me inside subscript syntax. Maybe not to others? The “default” parameter name helps, but then again, I’m still left wondering “why not use ?? ?”.