There is a Bool.toggle() function which makes code more verbose and obvious. Same thing can be used for Set. If you need to change the state of one of the elements, add or remove it, avoiding boilerplate code. For example if you have filter or settings list in UI.
extension Set {
mutating func toggle(_ element: Element) {
if self.contains(element) {
self.remove(element)
} else {
self.insert(element)
}
}
}
// how to use it
itemsSet.toggle(item)
If you don’t want to add an extension, there is a built-in Swift function:
itemsSet.formSymmetricDifference([item])