我怎样才能在Swift谓词中组合一个混合与或条件。我有以下查询
Select * from tblTemp where dept == 1 && (subdept == 11 || subdept == 12)
Run Code Online (Sandbox Code Playgroud)
我可以用相同的运算符写两个谓词,但不知道如何组合它们
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])
Run Code Online (Sandbox Code Playgroud)
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])
Run Code Online (Sandbox Code Playgroud)
或者,%ld对整数使用格式:
let deptPredicate = NSPredicate(format: "dept == %ld", 1)
// ... etc.
Run Code Online (Sandbox Code Playgroud)
还有便捷的初始化程序:
let orPredicate = NSCompoundPredicate(orPredicateWithSubpredicates:
[subdeptPredicate1, subdeptPredicate2])
let andPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:
[deptPredicate, orPredicate])
Run Code Online (Sandbox Code Playgroud)
复合谓词对于在运行时组合一组动态条件非常有用。另一方面,如果只有值更改,则可以在谓词格式字符串中简单地使用“ AND”和“ OR”:
NSPredicate(format: "dept == %ld AND (subdept = %ld OR subdept = %ld)", 1, 11, 12)
Run Code Online (Sandbox Code Playgroud)
最后请注意,可以将#keyPath指令与
%K占位符一起使用,以便编译器填写正确的属性名称(从而减少印刷错误的可能性):
let deptPredicate = NSPredicate(format: "%K == %ld", #keyPath(MyEntity.dept), 1)
Run Code Online (Sandbox Code Playgroud)