gpt4 book ai didi

Swift 组合谓词 LogicalType AND OR

转载 作者:可可西里 更新时间:2023-11-01 00:33:29 27 4
gpt4 key购买 nike

我如何在 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])

最佳答案

NSCompoundPredicateNSPredicate 的子类,也就是说结果是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)

关于Swift 组合谓词 LogicalType AND OR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48408023/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com