Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored property type 'CGPoint' does not conform to protocol 'Hashable',

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?

like image 489
Duck Avatar asked Sep 12 '25 07:09

Duck


2 Answers

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)
  }
}
like image 67
Duck Avatar answered Sep 13 '25 22:09

Duck


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 }
  }
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!