0

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"?

1

1 Answer 1

3

json is an array of dictionary with a key of "episode".

Don't use NSArray in Swift.

Update your code as follows:

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
}

Note the two changes: the cast and the way to access the "episode". Also note the use of == for equality.

Sign up to request clarification or add additional context in comments.

3 Comments

Actually the array is [[String:String]]
This works for me! Thank you for the very clear answer, and I learned something.
@vadian I considered that but wasn't 100% sure. That would be a good change if it turns out to be true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.