This is a construct I come across quite a lot. Is there a nice way to one-line it in Swift?
I could just write an extension on Sequence for it, but I feel like there's a "obvious" higher-order-function / set theory technique that is eluding me.
if array.contains(element) {
array.removeObject(object: element)
}
else {
array.append(element)
}
I don't think the solution will even necessarily be nicer per se, it's just something I think about every time I have to write this.
Set
instead? – Athenaarray.contains(element) ? array.removeObject(object: element) : array.append(element)
– Handbarrow//Technically one line 😂
– Glochidiateif array.contains(element) { array.removeObject(object: element) } else { array.append(element) }
– AmidoremoveObject
in Swift. – MothballO(n)
, and undoubtedly called as part of some loop that's at leastO(n)
.O(n^2)
explodes pretty fast, at very common real life data sets. People have thousands of songs, contacts, 10s/100s of thousands of files, etc. – Backwash