Swift sets have similar behaviour to Java sets when it comes to mutable objects: if you have a mutable object, wherein mutation of the object can result in a change to the hash value, that can lead to surprising behaviour. The collection may store the object in a bucket based on the hash it had at the time of insertion. If you modify the object, the hash value changes, but it doesn't move from one bucket to another. This can mean that a set may report that the object is not present even when it is.
I made a little playground (raw view, compressed form for download) to demonstrate this issue, but in essence:
let mi = MutableInt(1) let mis:Set = [mi] mis.contains(mi) // true mi.value = 2 mis.contains(mi) // false
The same object is present in the same set for both contains calls, but because the hash value has changed, the set can no longer find it.
No comments:
Post a Comment