我可能遗漏了一些东西(新的),但我正在使用这个 Swift 3 answer关于如何在 NSArray.
具体来说,我想从一个 JSON 数组返回与名为“episode”的属性匹配的值(这些是字符串):
let url = URL(string: "http://www.example.com/example.json")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
let json: Any?
do{
json = try JSONSerialization.jsonObject(with: data, options: [])
}
catch{
return
}
guard let data_list = json as? NSArray else {
return
}
if let foo = data_list.first(where: {$0.episode = "Example 1A"}) {
// do something with foo
print(foo)
} else {
// item could not be found
}
}).resume()
即使在遵循 XCode 并使用 AnyObject
(首先使用 Any
)之后,它仍然说 Value of type 'Any' has no member 'episode'
.
我认为这是因为我是从 URL 中提取它的,所以它不知道 episode
是一个真正的成员。我使用的数组如下所示:
[{"show": "Example", "episode": "Episode 1A", "date":"January 23"},{"show": "Example 2", "episode": "Episode 2B", "日期":"12月20日"
关于返回与我指定的 episode
字符串匹配的行(例如“Episode 1A”)的适当方法,您有什么想法吗?
最佳答案
json
是一个字典数组,键为"episode"
。
不要在 Swift 中使用 NSArray
。
按如下方式更新您的代码:
guard let data_list = json as? [[String:Any]] else {
return
}
if let foo = data_list.first(where: {$0["episode"] as? String == "Example 1A"}) {
// do something with foo
print(foo)
} else {
// item could not be found
}
请注意两个变化: Actor 阵容和访问“剧集”的方式。还要注意使用 ==
来表示相等。
关于ios - 使用来自 URL 的 JSON 数组并返回与 Swift 3 中的值匹配的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48410919/