拥有包含所有会话的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)
}
}
conversationationsArray填写如下:
[{
Id = "94cc96b5-d063-41a0-ae03-6d1a868836fb";
DeviceOnline = 1;
}, {
Id = "4b321903-af6a-405d-ac4f-c0799a7f714a";
DeviceOnline = 1;
}]
然后我创建一个messagesArray,其中包含一个值为:
的Dictionaryfunc 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添加到conversationsArray(通过创建新密钥:“Messages”,并使用messagesArray填充值)非常简单,但我似乎无法让它工作。我已经尝试过for循环来完成对话,但是我一直在弄错类型和东西。
conversationsArray的最终结果应该是这样的:
[{
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"
}]
}]
有人能指出我正确的方向,因为我必须在这里找到一些非常简单的东西。谢谢!
答案 0 :(得分:1)
由于您知道所有字典键都是String
,因此将两个数组定义为更具体的类型
[Dictionary<String,AnyObject>]()
答案 1 :(得分:0)
我在这里寻求最简单的解释,但如果你得到错误:
mongo::BSONObj* curr_elem=new mongo::BSONObj();
(*curr_elem)=cursor->next().getOwned(); //or: next().copy();
不会尝试将数组转换为AnyObject工作吗?
Cannot assign a value of type '[String: AnyObject]' to a value of type AnyObject