2019-06-19
How do i use array.filter to filter a class object based on a property?
stackoverflow
Question

I'm trying to filter an array of instances of a class. I'd like a new array filtered by one of the class properties. Can't quite get my head around the way Swift filters work for this use case.

enum Gender {
    case male,female
}

class Person {
    let name:String
    let gender:Gender
    init(name:String,gender:Gender) {
        self.name = name
        self.gender = gender
    }
}


let people = [Person.init(name: "James", gender: .male),
              Person.init(name: "John", gender: .male),
              Person.init(name: "Sally", gender: .female)
             ]

let males = people.filter( something )
Answer
1

This should work...

let males = people.filter({ $0.gender == .male })

You may need to make your enum conform to equatable to do this comparison.

The $0 is an unnamed parameter, you could also do..

let males = people.filter({ person in return person.gender == .male })

EDIT: I've just tested this and it does work without making the enum conform to equatable. I think you only need to do that when the enum takes parameters.

How do i use array.filter to filter a class object based on a property?
See more ...