I might be missing something (new to this) but I am using this Swift 3 answer on how to find an object in a NSArray.
Specifically, I want to return values from a JSON array that match a property called 'episode' (these are strings):
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()
Even after following XCode and using AnyObject (first used Any), it says that Value of type 'Any' has no member 'episode'.
My belief is this is because I am pulling this from a URL and so it doesn't know episode is a real member. The array I am using looks like this:
[{"show": "Example", "episode": "Episode 1A", "date":"January 23"},{"show": "Example 2", "episode": "Episode 2B", "date":"December 20"}
Any ideas what the appropriate way to return rows that match the episode string I specify, like "Episode 1A"?
Codableprotocol and serialize/deserialize your custom objects much more simply. See developer.apple.com/documentation/foundation/…