带条件的快速过滤器

时间:2018-08-13 10:11:48

标签: ios swift

我正在创建一个过滤器以过滤一系列车辆。我正在根据价格,性能以及(可选)齿轮类型进行过滤。

func filterCarSpecifications(among carSpecifications: [CarSpecification]) -> [CarSpecification] {

    let filteredCars = carSpecifications.filter {

        let performance = $0.car.ps ?? 0.0

        return $0.pricing.price >= IoC.filterDataService.selectedMinPrice.rounded(.down)
            && $0.pricing.price <= IoC.filterDataService.selectedMaxPrice.rounded(.up)
            && performance >= IoC.filterDataService.selectedMinPerformance
            && performance <= IoC.filterDataService.selectedMaxPerformance
    }

    if IoC.filterDataService.autoTransmision {
        return filteredCars.filter {
            let transmission: GearingType = .automatic
            return $0.car.gearingType == transmission
        }
    }

    return filteredCars
}

IoC.filterDataService.autoTransmision是一个布尔型控件,用于检查用户是否只想看到自动驾驶汽车。有没有办法将这个额外的值包含到我的原始过滤器中?

3 个答案:

答案 0 :(得分:1)

像这样附加它

php7.2

答案 1 :(得分:1)

追加

&& IoC.filterDataService.autoTransmision ? $0.car.gearingType == .automatic : true

恢复您的初始状况

答案 2 :(得分:1)

您可以这样写:

func filterCarSpecifications(among carSpecifications: [CarSpecification]) -> [CarSpecification] {

    let filteredCars = carSpecifications.filter {

        let performance = $0.car.ps ?? 0.0

        return $0.pricing.price >= IoC.filterDataService.selectedMinPrice.rounded(.down)
            && $0.pricing.price <= IoC.filterDataService.selectedMaxPrice.rounded(.up)
            && performance >= IoC.filterDataService.selectedMinPerformance
            && performance <= IoC.filterDataService.selectedMaxPerformance
            && (!IoC.filterDataService.autoTransmision || $0.car.gearingType == .automatic)
    }

    return filteredCars
}

IoC.filterDataService.autoTransmision == false时,||运算符的左侧变为true,因此忽略了右侧。

当它是true时,!IoC.filterDataService.autoTransmision变成false。您知道false || someBoolValue等同于someBoolValue

因此,$0.car.gearingType == .automatic仅在IoC.filterDataService.autoTransmision == true时被评估。