Thilo
Thilo

Reputation: 262774

Swift: Optional chaining for optional subscripts

I have a let map : [String: String] and a let key: String?.

What is the most concise way to access map[key] (and get back a String? if I had a key and None if I did not)?

Upvotes: 0

Views: 435

Answers (2)

Martin R
Martin R

Reputation: 539975

let value = key.flatMap { map[$0] }

would to the trick, using the

/// Returns `nil` if `self` is nil, `f(self!)` otherwise.
@warn_unused_result
public func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?

method from struct Optional.

Alternatively, you can wrap that into a custom subscript method

extension Dictionary {
    subscript(optKey : Key?) -> Value? {
        return optKey.flatMap { self[$0] }
    }
}

and the simply write

let value = map[key]

To avoid confusion with the "normal" subscript method, and to make the intention more clear to the reader of your code, you can define the subscript method with an external parameter name:

extension Dictionary {
    subscript(optional optKey : Key?) -> Value? {
        return optKey.flatMap { self[$0] }
    }
}

let value = map[optional: key]

Upvotes: 6

Thilo
Thilo

Reputation: 262774

I think I am going with the decidedly unfancy

key == nil ? nil : map[key!]

Upvotes: 0

Related Questions