在symmetricDifference之后Set中的重复项

时间:2017-08-14 12:41:24

标签: swift set

我有一些套装,我想创建symmetricDifference:

class Message: NSObject, NSCopying {
    let id: String
    var content: String

    public init(id: String, content: String) {
        self.id = id
        self.content = content

        super.init()
    }

    override var hashValue: Int {
        return self.id.hashValue ^ self.content.hashValue
    }

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

    override var description: String {
        return "ID: \(self.id) CONTENT: \(self.content)"
    }

    func copy(with zone: NSZone? = nil) -> Any {
        return Message(id: self.id, content: self.content)
    }
}

var originalMessages: Set<Message> = Set<Message>()

let message1 = Message(id: "12", content: "testje")
let message2 = Message(id: "13", content: "testje")
let message3 = Message(id: "14", content: "testje")

originalMessages.insert(message1)
originalMessages.insert(message2)
originalMessages.insert(message3)

print("Original messages")
print(originalMessages)

var newMessages: Set<Message> = Set<Message>()
let message4 = Message(id: "13", content: "testje")
let message5 = Message(id: "15", content: "testje")
newMessages.insert(message4)
newMessages.insert(message5)

print("New messages")
print(newMessages)

let newMessagesAndMessages = originalMessages.symmetricDifference(newMessages)

print("SymmetricDifference originalMessages and newMessages")
print(newMessagesAndMessages)

我得到的是:

Original messages
[ID: 12 CONTENT: testje, ID: 14 CONTENT: testje, ID: 13 CONTENT: testje]
New messages
[ID: 15 CONTENT: testje, ID: 13 CONTENT: testje]
SymmetricDifference originalMessages and newMessages
[ID: 12 CONTENT: testje, ID: 13 CONTENT: testje, ID: 14 CONTENT: testje, ID: 15 CONTENT: testje, ID: 13 CONTENT: testje]

我希望项目13只在集合中出现一次。

为什么我有两次相同的项目?

0 个答案:

没有答案