swift - 如何将值附加到字典内的字典中(Swift 4)

标签 swift dictionary caching

我正在尝试创建一个消息缓存,其结构就像这样的字典......

var messageCache = [String:[String:Message]]()

它基本上是[Conversation Id: [Message Id: Message]],并且Message也是一个值的字典。

每当我想将新的消息对象添加到我调用的消息缓存时

let messageKey = snapshot.key
let message = Message(dictionary: dictionary)

messageCache[convoId] = [messageKey:message]

但是,我相信这会删除 messageCache[convoId] 内的所有内容,并将其替换为一个消息 key 和对象。我也尝试过下面的代码,但它返回零。

messageCache[convoId]?[messageKey] = message

如何将另一个包含 [messageKey:Message] 的字典追加到 messageCache[convoId] 中?

最佳答案

也许这有帮助:

typealias MessageCacheeValue = (String, Message)

var messageCache = [String:[MessageCacheeValue]]()

let messageKey = snapshot.key
let message = Message(dictionary: dictionary)

let newValue = (messageKey, message)

if messageCache[convoId] == nil {
    messageCache[convoId] = [newValue]
} else {
    messageCache[convoId]?.append(newValue)
}

现在,messageCache 是一个由字符串键和元组数组值组成的字典。

关于swift - 如何将值附加到字典内的字典中(Swift 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51733409/

相关文章:

c - 拼写检查程序问题

python - 按值对字典进行排序,然后将排序后的值附加到文本文件中

image - 在浏览器中缓存图像

html - 我无法快速解码来自 HTML 页面的数据

java - 具有多个类的上限 - Java 泛型

scala - 从 scala 代码中使用 Google guava 时出现编译器错误

docker - 从 Jenkinsfile 启动时,Gradle docker 容器忽略缓存

ios - NSLocalizedString 没有获取键的值

ios - 什么是 UserNotification 框架相当于 didReceive 通知 : UILocalNotification?

json - 如何将 Swift 对象序列化或转换为 JSON?