我在使用以下代码时遇到一些问题,为什么它不起作用的任何想法?
guard let parsedData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments),
let parsedDict = parsedData as? [String:Any],
let stop = parsedDict["Stop"] as? [String:Any],
let name = stop["Name"] as? String,
let latitude = stop["Latitude"] as? String,
let longitude = stop["Longitude"] as? String else
{
print("Something Went Wrong")
return
}
nameArray.append(name)
latArray.append(latitude)
longArray.append(longitude)
但是,以下代码确实有效:
if let parsedData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
{
if let stop = parsedData?["Stop"] as? [String:Any]
{
if let latitude = stop["Latitude"] as? String, let longitude = stop["Longitude"] as? String, let name = stop["Name"] as? String
{
nameArray.append(name)
latArray.append(latitude)
longArray.append(longitude)
}
}
}
修改
在审核代码之后,问题似乎源于这一行:
guard let stop = parsedDict["Stop"] as? [String:Any] else
{
print("Something went wrong")
return
}
运行时,我在控制台中收到“出问题”,但运行时
if let stop = parsedData?["Stop"] as? [String:Any]
{
print(stop)
}
我得到了有效的停止打印。
答案 0 :(得分:0)
我自己在操场上运行你的守卫示例对我来说是成功的。我建议将你的警卫分成多个逻辑部分。例如,为了帮助您追踪错误,您可以将其更改为:
//Note: You should not force unwrap data here
guard let parsedData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) else{
print("Serialization error"); return
}
guard
let parsedDict = parsedData as? [String:Any],
let stop = parsedDict["Stop"] as? [String:Any] else {
print("Error casting to dictionary"); return
}
guard
let name = stop["Name"] as? String,
let latitude = stop["Latitude"] as? String,
let longitude = stop["Longitude"] as? String else {
print("Error casting dictionary values"); return
}
//Everything is ok here