Determining if Swift dictionary contains key and obtaining any of its values

前端 未结 7 1565
离开以前
离开以前 2020-11-30 17:04

I am currently using the following (clumsy) pieces of code for determining if a (non-empty) Swift dictionary contains a given key and for obtaining one (any) value from the

7条回答
  •  孤独总比滥情好
    2020-11-30 17:54

    Looks like you got what you need from @matt, but if you want a quick way to get a value for a key, or just the first value if that key doesn’t exist:

    extension Dictionary {
        func keyedOrFirstValue(key: Key) -> Value? {
            // if key not found, replace the nil with 
            // the first element of the values collection
            return self[key] ?? first(self.values)
            // note, this is still an optional (because the
            // dictionary could be empty)
        }
    }
    
    let d = ["one":"red", "two":"blue"]
    
    d.keyedOrFirstValue("one")  // {Some "red"}
    d.keyedOrFirstValue("two")  // {Some "blue"}
    d.keyedOrFirstValue("three")  // {Some "red”}
    

    Note, no guarantees what you'll actually get as the first value, it just happens in this case to return “red”.

提交回复
热议问题