對我來說,唯一的辦法就是增加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
但等於什麼?如果乘以'Obj'具有相同的代碼會發生什麼?例如,如果你有多個'Obj',輸出的代碼是'[「aaa」,「aba」,「aaa」,「aba」,「abc」,「xyz」,ard「]',那麼輸出是什麼?輸出爲'[「aaa」,「aaa」,「aba」,「aba」]'? – mhergon
由於'Obj1'是一個類,所以需要區分等於和相等。 –
'[Obj2] in such一個方法,該數組只包含Obj2的codeObj.code是等於什麼? – Alexander