Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 478
Insou Avatar asked May 31 '16 09:05

Insou


2 Answers

Swift 4.1 (and above) Updated answer:

Starting from Swift 4.1, all you have to is to conform to the Equatable protocol without the need of implementing the == method. See: SE-0185 - Synthesizing Equatable and Hashable conformance.

Example:

struct MyStruct: Equatable {
    var id: Int
    var value: String
}

let obj1 = MyStruct(id: 101, value: "object")
let obj2 = MyStruct(id: 101, value: "object")

obj1 == obj2 // true


Keep in mind that the default behavior for the == is to compare all the type properties (based on the example: lhs.id == rhs.id && lhs.value == rhs.value). If you are aiming to achieve a custom behavior (comparing only one property for instance), you have to do it by yourself:

struct MyStruct: Equatable {
    var id: Int
    var value: String
}

extension MyStruct {
    static func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
        return lhs.id == rhs.id
    }
}

let obj1 = MyStruct(id: 101, value: "obj1")
let obj2 = MyStruct(id: 101, value: "obj2")

obj1 == obj2 // true

At this point, the equality would be based on the id value, regardless of what's the value of value.

like image 121
Ahmad F Avatar answered Nov 02 '22 01:11

Ahmad F


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 :)

like image 24
Insou Avatar answered Nov 02 '22 01:11

Insou