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

前端 未结 7 1562
离开以前
离开以前 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:48

    My solution for a cache implementation that stores optional 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
    

提交回复
热议问题