Filter by multiple array conditions

后端 未结 2 1357
清歌不尽
清歌不尽 2020-12-30 07:27

The filter method is a really powerful tool for filtering by single or multiple conditions, but is there a way to filter by conditions of arrays?

class

2条回答
  •  清酒与你
    2020-12-30 08:02

    Forget about the filter for a moment. Think how you would check if a car's color is a value in an array.

    let colors = [ "Green", "Blue" ]
    // or let colors: Set = [ "Green", "Blue" ]
    if colors.contains(someCar.color) {
    }
    

    Simple enough. Now use that same simple expression in the filter.

    let filterdObject = cars.filter { $0.model == currModel || colors.contains($0.color) }
    

提交回复
热议问题