Swift Set union合并操作,如何去重

如题,我想重写判断相等的方法,然后按照我的逻辑来进行去重。代码如下:

class Media: NSObject {
    var name = ""
    var serialNumber = ""
    
    init(name: String, serialNumber: String) {
        self.name = name
        self.serialNumber = serialNumber
    }
    
    override func isEqual(_ object: Any?) -> Bool {
        guard let other = object as? Media else {
            return false
        }
        return name == other.name && serialNumber == other.serialNumber
    }
}
func ==(lhs:Media, rhs: Media) -> Bool {
    return lhs.name == rhs.name && lhs.serialNumber == rhs.serialNumber
}

let media1 = Media(name: "Media1", serialNumber: "Serial1")
let media2 = Media(name: "Media1", serialNumber: "Serial1")
let media3 = Media(name: "Media2", serialNumber: "Serial1")
let media4 = Media(name: "Media4", serialNumber: "Serial1")
        
let set1 = Set<Media>(arrayLiteral: media1, media3)
let set2 = Set<Media>(arrayLiteral: media2, media4)
        
let newSet = set1.union(set2)
        
print(newSet.count)

然后输出会有时是3,有时是4.这个我觉得特别奇怪。根据输出是通过isEqual方法来判断的,但是这个结果的不定性我不知道怎么办。

问题是,如何通过override的方式来控制【判断相等】的依据

查看回复