使用内部数组和另一个数组过滤对象数组

时间:2019-06-13 16:33:38

标签: arrays swift

让我们使用以下代码示例详细说明我的问题:

struct exampleObj {
    var str: String?
    var arr: [String]?
}

let filterArray = ["something1", "ins1", "something2"]

let obj1 = exampleObj(str: "obj1", arr: ["ins2", "ins3"])
let obj2 = exampleObj(str: "obj2", arr: ["ins1", "ins2"])
let obj3 = exampleObj(str: "obj3", arr: ["ins1", "ins4"])
let obj4 = exampleObj(str: "obj4", arr: ["ins3", "ins4"])

var arrayObj = [obj1, obj2, obj3, obj4]

let result = arrayObj.filter { filterArray.contains($0.arr...)} //??? I get lost here, dunno if right approach.

我想做的是通过使用另一个数组arrayObj来过滤filterArray,结果是在result上仅包含{{1 }}。

我希望我很清楚。对此问题有任何疑问,我在这里。

4 个答案:

答案 0 :(得分:1)

尝试一下:

let result = arrayObj.filter { obj in
    filterArray.contains { filter in
        obj.arr?.contains(filter) ?? false
    }
}

或使用Set

let result = arrayObj.filter { !Set(filterArray).isDisjoint(with: $0.arr ?? []) }

答案 1 :(得分:1)

您需要找到两个数组的值之间有交点的匹配项。使用集合更容易做到这一点。您还需要处理arr是可选的。

let result = arrayObj.filter { !Set(filterArray).intersection($0.arr ?? []).isEmpty }

如果您将filterArray声明为Set开始,这将更加有效。

let filterSet: Set = ["something1", "ins1", "something2"]

let obj1 = exampleObj(str: "obj1", arr: ["ins2", "ins3"])
let obj2 = exampleObj(str: "obj2", arr: ["ins1", "ins2"])
let obj3 = exampleObj(str: "obj3", arr: ["ins1", "ins4"])
let obj4 = exampleObj(str: "obj4", arr: ["ins3", "ins4"])

var arrayObj = [obj1, obj2, obj3, obj4]

let result = arrayObj.filter { !filterSet.intersection($0.arr ?? []).isEmpty }

答案 2 :(得分:1)

您只需在non-emptyintersection之间找到filterArray exampleObj's arr,即可完成操作,即

let filterSet = Set(filterArray)
let result = arrayObj.filter { (exampleObj) -> Bool in
    if let arr = exampleObj.arr {
        return !filterSet.intersection(arr).isEmpty
    }
    return false
}

输出:result包含obj1obj2

答案 3 :(得分:-1)

尝试一下

let result = arrObj.filter{ $0.arr.contains{ where : $0 as? String ?? "" == "ins1"} }