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

当前回答

接受的回答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?例如。

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

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

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

如果你正在处理的字典可能包含一个键的nil值,那么你可以通过以下方法检查key的存在:

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

获取字典中的第一个值:

dictionay.first?.value // optional since dictionary might be empty
if dictionayTemp["quantity"] != nil
    {

  //write your code
    }