Arrays 检索具有类似属性的对象的数组

Arrays 检索具有类似属性的对象的数组,arrays,swift3,filtering,Arrays,Swift3,Filtering,我的两个对象(Obj1和Obj2)定义如下: class Obj1: NSObject { var code : String init(code: String) { self.code = code } } class Obj2: NSObject { var codeObj : Obj1 var value : Double init(primary: Currency, value: Double) { self.prima

我的两个对象(Obj1和Obj2)定义如下:

class Obj1: NSObject {
   var code : String

   init(code: String) {
     self.code = code
   }
}


class Obj2: NSObject {
   var codeObj : Obj1
   var value : Double

   init(primary: Currency, value: Double) {
     self.primary = primary
     self.value = value
   }
}
我有一个Obj2数组,我正在尝试更新数组
[Obj2]
,以便该数组只包含codeObj.code相等的Obj2。在这方面包括Equalable协议会有帮助吗

我试过这个:

  let filteredArray =  array1.filter( { (c1: Obj2) -> Bool in
                return conversion2.contains(where: { (c2: Obj2) -> Bool in
                    return c1.codeObj.code == c2.codeObj.code;
                })
            }) + array2.filter( { (c2: Obj2) -> Bool in
                return conversion1.contains(where: { (c1: Obj2) -> Bool in
                    return c1.codeObj.code == c2.codeObj.code;
                })
            })

有什么方法可以简化这一点吗?

对我来说,唯一的方法是向以下对象添加
equalable

class Obj1: NSObject {
    var code : String

    init(code: String) {
        self.code = code
    }

    static func ==(lhs: Obj1, rhs: Obj1) -> Bool {
        return lhs.code == rhs.code
    }

}


class Obj2: NSObject {
    var codeObj : Obj1
    var value : Double

    init(obj: Obj1, value: Double) {
        self.codeObj = obj
        self.value = value
    }

    static func ==(lhs: Obj2, rhs: Obj2) -> Bool {
        return lhs.codeObj == rhs.codeObj
    }

}
要过滤相等值,请使用例如:

// Test objects
let obj1A = Obj1(code: "aaa")
let obj1B = Obj1(code: "aba")
let obj1C = Obj1(code: "aaa")
let obj1D = Obj1(code: "cca")
let obj1E = Obj1(code: "aba")
let obj1F = Obj1(code: "xca")

let obj2A = Obj2(obj: obj1A, value: 12.0)
let obj2B = Obj2(obj: obj1B, value: 12.0)
let obj2C = Obj2(obj: obj1C, value: 23.0)
let obj2D = Obj2(obj: obj1D, value: 46.0)
let obj2E = Obj2(obj: obj1E, value: 23.0)
let obj2F = Obj2(obj: obj1F, value: 4.0)

var array = [obj2A, obj2B, obj2C, obj2D, obj2E, obj2F]

var onlyEqual = [Obj2]()
for object in array {
    let count = array.filter({ $0 == object }).count
    if count > 1 {
        onlyEqual.append(object)
    }
}
其中
onlyEqual
包含:

aaa 
aba
aaa 
aba

但等于什么?如果乘法
Obj
具有相同的代码,会发生什么情况?例如,如果您有多个
Obj
,并且这些代码
[“aaa”、“aba”、“aaa”、“aba”、“abc”、“xyz”、“ard”]
,那么输出是什么?输出是
[“aaa”、“aaa”、“aba”、“aba”]
,并且由于
Obj1
是一个类,您需要区分相等和相同。
[Obj2]在这种情况下,数组只包含其codeObj.code等于的Obj2
等于什么?@mhergon Yes@DanielT我试图通过查看[Obj2]@Alexander[Obj2]的
codeObj.code
是否等于来过滤数组将具有Obj2,其
codeObj.code
等于其他元素的
codeObj.code
。类似于排序数组