3

I am trying to use struct as my key for dictionary.

Code works for swift 2, however not for swift 3 as in the picture link.

Equatable Code:

Equatable Code

François Maturel
  • 5,884
  • 6
  • 45
  • 50
selcuk
  • 73
  • 1
  • 10

2 Answers2

4

Any Swift type that conforms the Hashable protocol must also conform the Equatable protocol. Because Hashable protocol is inherited from Equatable protocol(source). That's why you are getting that error message.

As for your question, == function must be declared globally since you are overriding global == operator to be able to compare two Attributes you defined. With Swift 3, you can also define == in the struct itself, but it has to be static.

struct Attributes: Hashable {
  var uid: Int
  var size: Size
  var mimeType: mimeType

  var hashValue: Int {
      return uid
  }

  static func ==(lhs: Attributes, rhs: Attributes) -> Bool {
      return lhs.size == rhs.size && lhs.mimeType == rhs.mimeType
  }
}
ramazan polat
  • 7,111
  • 1
  • 48
  • 76
3

It's not about the Swift version. It will give error also on Swift 2. The problem is that you must define the == functions outside of the Struct because it must be a global function.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148