Search code examples
swiftstructprotocolsequatable

Swift Struct doesn't conform to protocol Equatable?


How do I make a structure conform to protocol "Equatable"?

I'm using Xcode 7.3.1

struct MyStruct {
   var id: Int
   var value: String

   init(id: Int, value: String) {
       self.id = id
       self.value = value
   }

   var description: String {
       return "blablabla"
   }

}

When I use "MyStruct", Xcode shows the error:

MyStruct does not conform to protocol "Equatable"

Do you have an idea to make MyStruct conform to protocol?


Solution

  • OK, after lots of searching, it's working...

    struct MyStruct {
        var id: Int
        var value: String
    
        init(id: Int, value: String) {
            self.id = id
            self.value = value
        }
    
        var description: String {
            return "blablabla"
        }
    
    }
    
    extension MyStruct: Equatable {}
    
    func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
        let areEqual = lhs.id == rhs.id &&
            lhs.value == rhs.value
    
        return areEqual
    }
    

    My Struct was in a class, so it didn't work.. I moved this Struct out of my class and now it's good :)