我目前使用以下(笨拙)段代码来确定是否一个(非空)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
}

当前回答

看起来你从@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”}

注意,不能保证您实际得到的第一个值是什么,它只是在这种情况下返回“red”。

其他回答

if dictionayTemp["quantity"] != nil
    {

  //write your code
    }

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

如果你想确保字典中根本不包含键,使用这个(在Swift 4中测试)。

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

我对存储可选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

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

看起来你从@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”}

注意,不能保证您实际得到的第一个值是什么,它只是在这种情况下返回“red”。