我正在创建一个过滤器以过滤一系列车辆。我正在根据价格,性能以及(可选)齿轮类型进行过滤。
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
是一个布尔型控件,用于检查用户是否只想看到自动驾驶汽车。有没有办法将这个额外的值包含到我的原始过滤器中?
答案 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
时被评估。