Hello, I want to implement such a thing. I have an enum with associated values and I am using for SwiftUI environment which will reflect that attributes, but my Set will overflow with unnecessary same cases. My main goal to achieve uniqueness of EnvironmentKey value by enum case ignoring associated value. Do I need custom struct that implement AlgebraSet?
public enum StyleAttribute: Hashable {
case tracking(CGFloat)
case kerning(CGFloat)
case baselineOffset(CGFloat)
}
This might be what you're looking for. You can create an inner enum that conforms to Equatable and Hashable, which matches StyleAttribute case-by-case but without any associated values, then write the custom conformance for Hashable/Equatable in terms of it! (not sure if this is the best way of achieving what you want, but it is a way)
public enum StyleAttribute {
case tracking(CGFloat)
case kerning(CGFloat)
case baselineOffset(CGFloat)
}
extension StyleAttribute: Equatable, Hashable {
// no associated values here
enum Key: Hashable, Equatable {
case tracking
case kerning
case baselineOffset
}
public static func == (lhs: StyleAttribute, rhs: StyleAttribute) -> Bool {
lhs.key == rhs.key
}
public func hash(into hasher: inout Hasher) {
hasher.combine(key)
}
// boilerplate for mapping
var key: Key {
switch self {
case .tracking: return .tracking
case .kerning: return .kerning
case .baselineOffset: return .baselineOffset
}
}
}
let setOfAttributes: Set<StyleAttribute> = Set([.kerning(1), .kerning(2), .baselineOffset(3)])
print(setOfAttributes)