Imagine a card board. All cards are on a view I call CardBoard.
All cards are on an array:
var cards:[Card]
Every card has its own position.
This is Card
struct Card: View {
let id = UUID()
var name:String
var code:String
var filename:String
var position = CGPoint(x: 200, y: 250)
init(name:String, code:String, filename:String) {
self.name = name
self.code = code
self.filename = filename
}
var body: some View {
Image(filename)
.position(position)
}
}
Now I want to draw them on the screen.
var body: some View {
ZStack {
ForEach(cards, id:\.self) {card in
}
}
}
when I try this, Xcode tells me
Generic struct 'ForEach' requires that 'Card' conform to 'Hashable'
when I add Hashable to Card
struct Card: View, Hashable {
1. Stored property type 'CGPoint' does not conform to protocol 'Hashable', preventing synthesized conformance of 'Card' to 'Hashable'
any ideas?
THANKS EVERYBODY, but because is not good to post a link as a solution, I am posting here:
The solution is to make the view Hashable and add this:
extension CGPoint : Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
}
There's a bunch of types that need the same treatment (which are often named 2-tuples). e.g.
extension CGPoint: HashableSynthesizable { }
extension CLLocationCoordinate2D: HashableSynthesizable { }
extension MKCoordinateRegion: HashableSynthesizable { }
extension MKCoordinateSpan: HashableSynthesizable { }
/// A type whose `Hashable` conformance could be auto-synthesized,
/// but either the API provider forgot, or more likely,
/// the API is written in Objective-C, and hasn't been modernized.
public protocol HashableSynthesizable: Hashable { }
public extension HashableSynthesizable {
static func == (hashable0: Self, hashable1: Self) -> Bool {
zip(hashable0.hashables, hashable1.hashables).allSatisfy(==)
}
func hash(into hasher: inout Hasher) {
hashables.forEach { hasher.combine($0) }
}
}
private extension HashableSynthesizable {
var hashables: [AnyHashable] {
Mirror(reflecting: self).children
.compactMap { $0.value as? AnyHashable }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With