我从服务器
收到一个对象var profileDictionary = users.allDocuments[0].valueForKey("profile")
print("profileDictionary: \(profileDictionary)")
看起来像底部的控制台输出。
我想更改[name] [first]字段(遗憾的是Elon还不是客户),并将对象发送回服务器以更新记录。我怎样才能做到这一点?
我试过了:
profileDictionary["name"]!["first"] as String = "Karlos"
但是它给出了错误:无法分配给'String'类型的不可变表达式
我也试过
profileDictionary!["name"]!!["first"] = "Karlos"
那么错误是: 无法分配给'AnyObject?'
类型的不可变表达式如果我将profileDictionary更改为NSDictionary
var profileDictionary = users.allDocuments[0].valueForKey("profile") as! NSDictionary
profileDictionary["name"]!["first"] = "Karlos"
我得到了同样的错误:无法分配给'AnyObject?'
类型的不可变表达式使用SwiftyJSON我可以很容易地改变一个值,但它会弄乱类型,例如将1变为真。
如何更改此对象中的值?
非常感谢任何帮助!谢谢。
控制台输出
Optional({
address = {
city = "";
country = nor;
lineOne = "";
lineTwo = "";
zip = "";
};
card = {
last4 = 4242;
verified = 1;
};
filledOut = 1;
name = {
first = Elon;
last = Musk;
};
phone = 911;
validated = 1;
})
答案 0 :(得分:2)
试试这个(完全快速实施):
var profileDictionary = ["address" : ["city" : "" , "country" : "nor" , "lineOne" : "" , "lineTwo" : "", "zip" : ""], "card" : ["last4" : 4242 , "verified" : 1] , "filledOut" : 1 , "name" : ["first" : "Elon" , "last" : "Musk"] , "phone" : 911 , "validated" : 1]
print(profileDictionary) // This prints first name as Elon
var nameDict = profileDictionary["name"] as! Dictionary<String,String>
nameDict["first"] = "Karlos"
profileDictionary["name"] = nameDict
print(profileDictionary) // This prints first name as Karlos
答案 1 :(得分:1)
试试这个;
if let profileDictionary:NSMutableDictionary = users.allDocuments[0].valueForKey("profile") as? NSMutableDictionary {
if let nameDict:NSMutableDictionary = profileDictionary["name"] as? NSMutableDictionary {
nameDict["first"] = "Karlos";
}
print("profileDictionary: \(profileDictionary)")
}