Swift Struct doesn't conform to protocol Equatable?

前端 未结 4 2034
轻奢々
轻奢々 2021-02-07 01:37

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


        
4条回答
  •  借酒劲吻你
    2021-02-07 02:22

    The issue isn't that the struct is within a class. That is certainly allowable, and there are many instances where you might want to do that. The issue is in the implementation of the Equatable protocol. You have to give a global implementation of == (which you have done), but there is no entity MyStruct....it is ParentClass.MyStruct (if the struct is defined within a parent class). The example below in itself is probably not a good example in this case, but it does show how you can do this if needed.

    class ParentClass {
    
      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 ParentClass.MyStruct: Equatable {}
    
    func ==(lhs: ParentClass.MyStruct, rhs: ParentClass.MyStruct) -> Bool {
      let areEqual = lhs.id == rhs.id &&
        lhs.value == rhs.value
    
      return areEqual
    }
    
    let s1 = ParentClass.MyStruct(id: 1, value: "one")
    let s2 = ParentClass.MyStruct(id: 2, value: "two")
    let s3 = ParentClass.MyStruct(id: 1, value: "one")
    
    s1.description    //blablabla
    
    s1 == s2         //false
    s3 == s1         //true
    

    Note: I like to implement Comparable rather than just Equatable, which will allow you to support sorting and other functionality.

提交回复
热议问题