如何在Swift谓词中组合混合AND OR条件。我有以下查询
Select * from tblTemp where dept == 1 && (subdept == 11 || subdept == 12)
我可以用相同的运算符编写两个谓词,但不知道如何组合它们
let deptPredicate = NSPredicate(format: "dept == %@", 1)
let subdeptPredicate1 = NSPredicate(format: "subdept = %@", 11)
let subdeptPredicate2 = NSPredicate(format: "subdept = %@", 12)
let andPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: [deptPredicate, subdeptPredicate1])
答案 0 :(得分:4)
NSCompoundPredicate
是NSPredicate
的子类,意思是
结果
NSCompoundPredicate(type:subpredicates:)
可用于其他化合物
谓词。
但请注意,%@
格式占位符需要NSObject
实例:
let deptPredicate = NSPredicate(format: "dept == %@", 1 as NSNumber)
let subdeptPredicate1 = NSPredicate(format: "subdept = %@", 11 as NSNumber)
let subdeptPredicate2 = NSPredicate(format: "subdept = %@", 12 as NSNumber)
let orPredicate = NSCompoundPredicate(type: .or,
subpredicates: [subdeptPredicate1, subdeptPredicate2])
let andPredicate = NSCompoundPredicate(type: .and,
subpredicates: [deptPredicate, orPredicate])
或者,对整数使用%ld
格式:
let deptPredicate = NSPredicate(format: "dept == %ld", 1)
// ... etc.
还有便利初始化器:
let orPredicate = NSCompoundPredicate(orPredicateWithSubpredicates:
[subdeptPredicate1, subdeptPredicate2])
let andPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:
[deptPredicate, orPredicate])
复合谓词对于组合动态集非常有用 运行时的条件。另一方面,如果只有值发生变化 那么你可以简单地在谓词中使用“AND”和“OR” 格式字符串:
NSPredicate(format: "dept == %ld AND (subdept = %ld OR subdept = %ld)", 1, 11, 12)
最后请注意,您可以使用#keyPath
指令
%K
占位符,以便编译器填充正确的属性
名称(从而减少印刷错误的可能性):
let deptPredicate = NSPredicate(format: "%K == %ld", #keyPath(MyEntity.dept), 1)