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

3
  • 2
    Please add the code as text, not as an image. Jul 7, 2016 at 10:54
  • The code cannot work in Swift 2 either. The error message is very clear: Operators are only allowed at global scope
    – vadian
    Jul 7, 2016 at 10:57
  • @appzYourLife will do next time
    – selcuk
    Jul 7, 2016 at 11:03

2 Answers 2

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

2
  • Thanks. First time working with Hashable, Equatable. Works nicely now.
    – selcuk
    Jul 7, 2016 at 11:05
  • @selcuk: Please read this Jul 7, 2016 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.