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

当前回答

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

其他回答

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

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

获取字典中的第一个值:

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

不需要任何特殊的代码就可以做到这一点,因为字典已经做到了。当你获取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
}

如果你想返回键的值,你可以使用这个扩展

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

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