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

前端 未结 2 1590
孤城傲影
孤城傲影 2020-12-07 00:07

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

2条回答
  •  余生分开走
    2020-12-07 00:58

    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.

提交回复
热议问题