Daniel Bramhall
Daniel Bramhall

Reputation: 1501

Searching Array of Dictionary Objects in Swift 2

I have an array of dictionary objects populated from a JSON file defined as:

var peopleArray = [Person]()

Person is defined as:

class Person {

    var name: String?
    var gender: String?
    var html_url: String?

    init(json: NSDictionary) { // Dictionary object
        self.name = json["name"] as? String
        self.gender = json["gender"] as? String
        self.html_url = json["html_url"] as? String // Location of the JSON file
    }
}

Once the array has been populated, I am struggling to use the contains function to determine whether there is someone with a specific name.

I am thrown the following error: Cannot convert value of type 'String!' to expected argument type '@noescape (Person) throws -> Bool' for the following line I've attempted:

if (peopleArray.contains("Bob"))

Upvotes: 1

Views: 62

Answers (1)

Alessandro Orrù
Alessandro Orrù

Reputation: 3513

You should use a closure as input parameter of contains call:

peopleArray.contains { person -> Bool in
    person.name == "Bob"
}

or with the short style syntax:

peopleArray.contains { $0.name == "Bob" }

Alternatively, if what you want is to look for a specific person, you could make Person conform to Equatable: https://stackoverflow.com/a/32953118/2227743

Upvotes: 4

Related Questions