2017-02-15 86 views
0

的對象,我有我的兩個對象數組(OBJ1 & OBJ2)數組只包含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; 
       }) 
      }) 

有沒有辦法簡化這個?

+0

但等於什麼?如果乘以'Obj'具有相同的代碼會發生什麼?例如,如果你有多個'Obj',輸出的代碼是'[「aaa」,「aba」,「aaa」,「aba」,「abc」,「xyz」,ard「]',那麼輸出是什麼?輸出爲'[「aaa」,「aaa」,「aba」,「aba」]'? – mhergon

+0

由於'Obj1'是一個類,所以需要區分等於和相等。 –

+0

'[Obj2] in such一個方法,該數組只包含Obj2的codeObj.code是等於什麼? – Alexander

回答

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 
相關問題