[英]Swift - Predicate to filter an array by a property of member array
I need to filter out an array of MyClass3 Objects. 我需要过滤掉一组MyClass3对象。 An array of MyClass2 Objects is a member of MyClass3 object(Please refer to code below).
MyClass2对象的数组是MyClass3对象的成员(请参阅下面的代码)。 MyClass2 object has an id.
MyClass2对象有一个id。 I have an idArray at hand.
我手边有一个idArray。 I need to filter out those MyClass3 objects in which all ids in idArray are present in its [MyClass2] member.
我需要过滤掉那些MyClass3对象,其中idArray中的所有id都存在于其[MyClass2]成员中。
class MyClass2 : NSObject {
var uid: Int = 0
init(uid : Int) {
self.uid = uid
}
}
class MyClass3 : NSObject {
var arr: [MyClass2]
init(units: [MyClass2]) {
arr = units
}
}
var units1 = [MyClass2(uid: 1),MyClass2(uid: 2), MyClass2(uid: 3), MyClass2(uid: 4), MyClass2(uid: 5)]
var units2 = [MyClass2(uid: 4),MyClass2(uid: 5), MyClass2(uid: 6)]
var units3 = [MyClass2(uid: 3),MyClass2(uid: 5), MyClass2(uid: 7), MyClass2(uid: 1)]
var ids = [1,5]
var available3: [MyClass3] = [MyClass3(units: units1), MyClass3(units: units2), MyClass3(units: units3)]
var filtered3: [MyClass3] = []
let searchPredicate: NSPredicate = NSPredicate(format: " ANY arr.uid IN \(ids)") // needed predicate
print(searchPredicate.predicateFormat)
filtered3 = (available3 as NSArray).filteredArrayUsingPredicate(searchPredicate) as! [MyClass3]
The required answer is that we need MyClass3(units: units1) and MyClass3(units: units3) in the filtered Array. 要求的答案是我们在过滤后的数组中需要MyClass3(单位:units1)和MyClass3(单位:units3)。
This is not working out. 这没有用。 Can someone suggest a predicate format for this purpose
有人可以为此目的建议谓词格式
Using string interpolation in predicate format strings is never a good idea. 在谓词格式字符串中使用字符串插值绝不是一个好主意。 The correct form of your predicate would be
你谓词的正确形式是
let searchPredicate = NSPredicate(format: "ANY arr.uid IN %@", ids)
However that checks if any of the uids is in the given list. 但是,检查是否有任何 uid在给定列表中。 To check if all uids are in the given list, the following predicate should work:
要检查所有 uid是否在给定列表中,以下谓词应该有效:
let searchPredicate = NSPredicate(format: "SUBQUERY(arr.uid, $x, $x IN %@).@count = %d", ids, ids.count)
The same can be achieved without predicates in "pure" Swift 3 as 如果没有“纯粹的”Swift 3中的谓词,也可以实现相同的目标
filtered3 = available3.filter { $0.arr.filter { ids.contains($0.uid) }.count == ids.count }
or 要么
filtered3 = available3.filter { Set(ids).isSubset(of: $0.arr.map { $0.uid }) }
You can do using perform intersection operation instead of NSPredicate: 您可以使用执行交集操作而不是NSPredicate:
Refer below link for this 请参阅以下链接
Set operations (union, intersection) on Swift array? 在Swift数组上设置操作(union,intersection)?
您可以查看此链接以获取良好示例,但是对于数组的过滤,您可以使用以下内容:
filteredArray = wholeArray.filter{ !unwantedArray.contains($0)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.