Swift: Optional chaining for optional subscripts

前端 未结 2 1526
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-27 06:51

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

相关标签:
2条回答
  • 2021-01-27 07:32

    I think I am going with the decidedly unfancy

    key == nil ? nil : map[key!]
    
    0 讨论(0)
  • 2021-01-27 07:38
    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]
    
    0 讨论(0)
提交回复
热议问题