Swift Set insert method replaces the element if it was already in the set.

Originator:simonracz
Number:rdar://24101520 Date Originated:08-Jan-2016
Status:Open Resolved:closed
Product:iOS SDK Product Version:
Classification: Reproducible:always
 
Summary:
Unlike NSMutableSet's addObject: method, Swift's Set's insert method replaces the element if it was already in the set.

Steps to Reproduce:
// Can be copied to a Playground

class Foo: Hashable, CustomStringConvertible {
    let value: Int
    let notPartOfValue: Int
    init(value: Int, notPartOfValue: Int) {
        self.value = value
        self.notPartOfValue = notPartOfValue
    }
    var hashValue: Int {
        return value.hashValue
    }
    var description: String {
        return "{Foo, v:\(value), n:\(notPartOfValue)}"
    }
}

func ==(lhs: Foo, rhs: Foo) -> Bool {
    return lhs.value == rhs.value
}

var s = Set<Foo>()
s.insert(Foo(value: 1, notPartOfValue: 100))
print(s)
s.insert(Foo(value: 1, notPartOfValue: 200))
print(s)


Expected Results:
Last line should print : "[{Foo, v:1, n:100}]\n"

Actual Results:
Last line prints "[{Foo, v:1, n:200}]\n"

Version:
Latest public xcode 7, Swift 2

Notes:
http://www.chaonis.com/2016/01/swift-set-vs-nsmutableset/

Configuration:
It doesn't matter

Attachments:

Comments

It's fixed in Swift 4.

By simonracz at July 5, 2017, 1:23 p.m. (reply...)

Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!