Filter by multiple array conditions

后端 未结 2 1348
清歌不尽
清歌不尽 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 07:45

    Treat the filter closures like a value type and store them in an array. Use the inner reduce call to create a single boolean value that is true is all of the conditions are met by the current car. If you need a compound test like color == "blue" or "green" then simply add that to your filter closure conditions array.

        struct Car {
          let model: String
          let color: String
        }
    
        let conditions: [(Car) -> Bool] = [
          {$0.model == "Opel"},
          {$0.color == "Red"},
        ]
    
        let carLot = [
          Car(model: "Opel", color: "Green"),
          Car(model: "Mustang", color: "Gold"),
          Car(model: "Opel", color: "Red"),
        ]
    
        let allRedOpels = carLot.filter {
          car in
          conditions.reduce(true) { $0 && $1(car) }
       }
    
    0 讨论(0)
  • 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) }
    
    0 讨论(0)
提交回复
热议问题