我在Xcode
中返回了一个数组,输出以下内容:
["userDetails": {
id = 31;
"user_email" = "steve@gmail.com";
"user_name" = "Steve Downs";
}, "communities": <__NSArrayI 0x600000245f40>(
{
id = 5;
name = South;
},
{
id = 13;
name = HurraHarry;
},
{
id = 15;
name = EnclliffeT;
}
)
]
以下代码正确地将“社区”中包含的值分配给各自的变量。
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print (json!)
if let arr = json?["communities"] as? [[String:String]] {
self.communitiesArray = arr.flatMap { $0["name"]!}
self.communityIdsArray = arr.flatMap { $0["id"]!}
}
if let arr = json?["userDetails"] as? [AnyObject] {
self.playerId = (arr.flatMap { $0["id"]!} as (AnyObject)) as! [String]
print (self.playerId);
}
但是,我在id
分配"userDetails"
时遇到问题。如何从id
获取"userDetails"
并将其分配给self.playerId?
答案 0 :(得分:0)
您可以尝试这样的事情
if let dict = json?["userDetails"] as? [String:String] {
self.playerId = dict["id"]
}
答案 1 :(得分:-1)
我认为正确的是:
guard let item = json?["userDetails"] as? [String: AnyObject],
self.playerId = item["id"] as? Int else {
return;
}