确定 Swift 字典是否包含键并获取其任何值

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

我目前正在使用以下(笨拙的)代码片段来确定(非空)Swift 字典是否包含给定键并从同一字典中获取一个(任何)值。

如何在 Swift 中更优雅地表达这一点?

// excerpt from method that determines if dict contains key
if let _ = dict[key] {
    return true
}
else {
    return false
}

// excerpt from method that obtains first value from dict
for (_, value) in dict {
    return value
}

您不需要任何 特殊代码来执行此操作,因为字典已经可以做到这一点。当您获取 dict[key] 时,您 知道 字典是否包含键,因为您取回的 Optional 不是 nil (并且它包含值)。

因此,如果您只是想回答字典是否包含关键字的问题,请问:

let keyExists = dict[key] != nil

如果您想要该值并且您知道字典包含键,请说:

let val = dict[key]!

但是,如果像通常发生的那样,您不知道它包含密钥 - 您想要获取它并使用它,但前提是它存在 - 然后使用类似 if let:

if let val = dict[key] {
    // now val is not nil and the Optional has been unwrapped, so use it
}

看起来你从@matt 那里得到了你需要的东西,但是如果你想要一种快速获取键值的方法,或者如果该键不存在则只获取第一个值:

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”}

请注意,不能保证您实际获得的第一个值是什么,在这种情况下它恰好是 return“红色”。

为什么不简单地检查 dict.keys.contains(key)? 在值为 nil 的情况下,检查 dict[key] != nil 将不起作用。 例如,与字典 [String: String?] 一样。

我的存储可选 NSAttributedString 的缓存实现的解决方案:

public static var attributedMessageTextCache    = [String: NSAttributedString?]()

    if attributedMessageTextCache.index(forKey: "key") != nil
    {
        if let attributedMessageText = TextChatCache.attributedMessageTextCache["key"]
        {
            return attributedMessageText
        }
        return nil
    }

    TextChatCache.attributedMessageTextCache["key"] = .some(.none)
    return nil
if dictionayTemp["quantity"] != nil
    {

  //write your code
    }

如果字典包含键但值为 nil,则接受的答案 let keyExists = dict[key] != nil 将不起作用。

如果您想确定字典中根本不包含键,请使用此键(已在 Swift 4 中测试)。

if dict.keys.contains(key) {
  // contains key
} else { 
  // does not contain key
}

如果你想return键的值你可以使用这个扩展

extension Dictionary {
    func containsKey(_ key: Key) -> Value? {
        if let index = index(forKey: key){
            return self.values[index]
        }
        return nil
    }
}

如果您处理的字典可能包含某个键的 nil 值,那么您可以通过以下方式检查键是否存在:

dictionay.index(forKey: item.key) != nil

获取字典中的第一个值:

dictionay.first?.value // optional since dictionary might be empty