有一个包含所有对话的JSON对象,以及一个包含来自特定对话的所有消息的JSON对象。解析这些JSON对象,然后将值放在Dictionary中,然后放在Array中。到目前为止,一切正常。
func didReceiveConversations(result: JSON) {
var conversationsArray = [AnyObject]()
for (key: String, subJson: JSON) in result["Data"] {
var conversationDictionary = [String: AnyObject]()
conversationDictionary["DeviceOnline"] = subJson["DeviceOnline"].boolValue
conversationDictionary["Id"] = subJson["Id"].stringValue
self.conversationsArray.append(conversationDictionary)
}
}
sessionsArray的填充如下:
[{
Id = "94cc96b5-d063-41a0-ae03-6d1a868836fb";
DeviceOnline = 1;
}, {
Id = "4b321903-af6a-405d-ac4f-c0799a7f714a";
DeviceOnline = 1;
}]
然后,我创建一个messagesArray,其中包含具有以下值的Dictionary:
func didReceiveResultSpecificConversation(result: JSON) {
var messagesArray = [AnyObject]()
for (key: String, subJson: JSON) in result {
var messageDictionary = [String: AnyObject]()
messageDictionary["MessageId"] = subJson["MessageId"].stringValue
messageDictionary["MessageText"] = subJson["MessageText"].stringValue
messagesArray.append(messageDictionary)
}
// I guess here comes the code to add the messages to the conversationsArray
// in the Dictionary under a key: "Messages" for example so I tried this:
for conversation in self.conversationsArray {
if conversation["Id"] as! String == messagesArray[0]["ConversationId"] as! String {
conversation["Messages"] = messagesArray as [String: AnyObject]
}
}
// This gives me: Cannot assign a value of type '[String: AnyObject]' to
// a value of type 'AnyObject?!'
messagesArray.removeAll(keepCapacity: false)
}
我认为现在将messagesArray添加到sessionsArrays中(通过创建一个新键:“ Messages”,并用messagesArray填充值)非常简单,但是我似乎无法使其正常工作。我在对话中尝试了一个for循环,但是我不断在类型和内容上出错。
sessionsArray的最终结果应该是这样的:
[{
Id = "94cc96b5-d063-41a0-ae03-6d1a868836fb";
DeviceOnline = 1;
Messages [{
MessageId = "1"
MessageText = "Foo"
},{
MessageId = "2"
MessageText = "Bar"
}]
}, {
Id = "4b321903-af6a-405d-ac4f-c0799a7f714a";
DeviceOnline = 1;
Messages [{
MessageId = "1"
MessageText = "Hello"
},{
MessageId = "2"
MessageText = "World"
}]
}]
有人可以指出正确的方向,因为我在这里肯定会错过一些非常简单的事情。谢谢!
最佳答案
因为您知道所有字典键都是String
,所以将两个数组的类型更具体地定义为
[Dictionary<String,AnyObject>]()
关于ios - Swift:想要将数组添加到现有字典中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32138719/