简体   繁体   English

包含字典的字典包含字典?

[英]Dictionary containing Arrays containing Dictionaries?

Code snippets: 代码段:

This is from a struct called Static : 这来自一个称为Static的结构:

static var messages: Dictionary = [:]

This is inside a class function: 这是在类函数内:

if Static.messages[sender] == nil{ //no message history, create array then append
    var messages: [NSMutableDictionary] = [message]
    Static.messages[sender] = messages
}
else{ //there is message history, so append
    (Static.messages[sender] as Array).append(message)
}

Error: 错误:

Immutable value of type 'Array<T>' only has mutating members named 'append'

I'm trying to make a Dictionary of conversations with each item being a person. 我正在尝试制作一个会话词典,每个项目都是一个人。 Each array will be a list of messages. 每个数组都是消息列表。 The messages are of type dictionary. 消息是字典类型。 Any idea why I'm getting this message? 知道我为什么收到此消息吗?

If you're clear with the compiler about what your dictionary contains, you won't need the cast that is making this difficult. 如果您对编译器很清楚字典中包含的内容,则不需要进行强制转换,这会使此工作变得很困难。 From what you've posted, the actual type of Static.messages will need to be something like Dictionary<NSObject, Array<NSMutableDictionary>> . 从您发布的内容Static.messagesStatic.messages的实际类型将需要类似于Dictionary<NSObject, Array<NSMutableDictionary>>

Your current attempt casts a dictionary value as an Array and then tries to append -- this fails because Swift treats the result of this kind of cast as immutable. 您当前的尝试将字典值转换为Array ,然后尝试追加-失败,因为Swift将这种转换结果视为不可变。 What you need to do instead is to simply use optional chaining: 您需要做的只是简单地使用可选链接:

// instead of:
(Static.messages[sender] as Array).append(message)

// use:
Static.messages[sender]?.append(message)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM