我想知道是否有任何捷径设定 colorPredicate 的价值
枚举颜色{ 案例黑色 案例白色 }
func predicateForColor(color: Color, compoundWith compoundPredicate: NSPredicate?) -> NSPredicate {
// NOTE: if I use the code bellow to set the value of colorPredicate, will got error: expected initial value after '='.
// let colorPredicate =
// switch color {
// case .black: return predicateForBlack()
// case .white: return predicateForWhite()
// }
func getPredicateByColor(color: Color) -> NSPredicate {
switch color {
case .black: return predicateForBlack()
case .white: return predicateForWhite()
}
}
let colorPredicate = getPredicateByColor(color: color)
if let predicate = compoundPredicate {
return NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, colorPredicate])
} else {
return colorPredicate
}
}
func predicateForBlack() -> NSPredicate {
print("get black predicate")
return NSPredicate(format: "color = black")
}
func predicateForWhite() -> NSPredicate {
print("get white predicate")
return NSPredicate(format: "color = white & someother condition")
}
print(predicateForColor(color: .black, compoundWith: nil))
答案 0 :(得分:0)
let colorPredicate: NSPredicate = { (color: Color) -> NSPredicate in
switch color {
case .black: return predicateForBlack()
case .white: return predicateForWhite()
}
}(color)
<强> 更新 强>
您的代码会产生错误,因为您需要编写:
let variable = { switch { ... } }()
而不是
let variable = switch { ... }
这样你就可以定义一个块并调用它,你不能从switch语句中分配它。
字典方法
设置:
var lookup: [Color: NSPredicate] = [:]
lookup[.black] = NSPredicate(format: "color = black")
lookup[.white] = NSPredicate(format: "color = white")
使用:
let colorPredicate = lookup[color]