一直致力于从API中提取数据,最终让它工作(我相信正确)但是当我在字典中打印出变量时,“Optional”会被添加到字符串中
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary
print(jsonResult)
if (jsonResult != nil) {
if let players = jsonResult?["players"] as? [Dictionary<String, AnyObject>] {
for player in players {
let personID = player["name"]
print(personID)
}
}
} else {
print("No Data")
// couldn't load JSON, look at error
}
}
JSON输出的示例:(注意我将其剪切并仅使用第一个元素)
Optional({
players = (
{
name = "Derek Anderson";
},
打印声明:
Optional(Derek Anderson)
我的假设是它打印可选词典,然后抓住“玩家”的名字。意思是我没有把这个名字拉出来。我已将名称从玩家阵列中拉出,而不是可选。
我觉得我可能会以某种方式添加可选数组,但似乎无法解决这个问题!
答案 0 :(得分:0)
解决了,变量需要解包:
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary
print(jsonResult)
if (jsonResult != nil) {
if let players = jsonResult?["players"] as? [Dictionary<String, AnyObject>] {
for player in players {
let personID = player["name"]!
print(personID)
}
}
} else {
print("No Data")
// couldn't load JSON, look at error
}
}