If I run the following code in a Swift playground it works as expected. That is, the "equatable" object is added only once, and "==" operator is called. However, if I paste the code in an app it adds the object twice. I gather I'm missing something obvious.
Xcode 11.5, Swift version 5.2.4.
Any help appreciated.
struct Object: Equatable, Hashable {
let name: String
let completed: Bool
static func == (lhs: Object, rhs: Object) -> Bool {
// Comparison operator called only in playground
print("Comparing \(lhs.name) == \(rhs.name)")
return lhs.name == rhs.name
}
public func hash(into hasher: inout Hasher) {
hasher.combine(name)
}
}
let firstObject = Object(name: "apples", completed: false)
let secondObject = Object(name: "apples", completed: true)
var set = Set<Object>()
set.insert(firstObject)
// set.insert(secondObject) // Adds "duplicate" object
set.update(with: secondObject) // Also adds "duplicate" object
print(set) // Why are two "equal" objects added to the set?
Playground output:
Comparing apples == apples
[__lldb_expr_5.Object(name: "apples", completed: true)]
App output:
[settest.ViewController.(unknown context at $106fd87bc).(unknown context at $106fd8808).Object(name: "apples", completed: false), settest.ViewController.(unknown context at $106fd87bc).(unknown context at $106fd8808).Object(name: "apples", completed: true)]
Also, if I add more properties or change the Bool to String the result is the same.