I have a type called FeildType
which is Equatable
, Hashable
, Identifiable
.
I use a type called UniqueID
as my identifier which is defined as below:
public struct UniqueID: Hashable , Equatable , Sendable {
public let fullName : String
public let parentName : String
public var id : String { parentName + "." + fullName }
public static func == (lhs: UniqueID, rhs: UniqueID) -> Bool {
return rhs.id == lhs.id
}
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
and FeildType
implemention is like this:
public final class FeildType : Identifiable , Hashable , Equatable {
/// id used for Hashable , Equatable
public var id : UniqueID { .init(fullName: fullName, parentName: parentType?.fullName ?? "" ) }
//....
}
public extension FeildType{
static func == (lhs: FeildType , rhs: FeildType) -> Bool {
lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
Now I compare 2 Set<FeildType>
s in my test case swift sometimes returns false even-though 2 sets have elements with identical id
s:
#expect(optionalInfo.fields.map(\.id).ascending()
== person.fields.map(\.id).ascending() ) //Always True
// Note: person.fields and optionalInfo.fields are not arrays, they are Set<FeildType>
#expect(optionalInfo.fields == person.fields) // Most of the times False
the questions is why? and more importantly why sometimes it fails and sometimes it doesn't?