使用类似属性的对象检索数组

时间:2017-02-15 21:25:57

标签: 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.primary = primary
     self.value = value
   }
}

我有一个Obj2数组,我正在尝试更新数组[Obj2],使数组只包含其codeObj.code相等的Obj2。将包括Equatable协议在内有帮助吗?

我试过这个:

  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;
                })
            })

有没有办法简化这个?

1 个答案:

答案 0 :(得分:0)

对我而言,唯一的方法是将equatable添加到对象中:

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