本文介绍了Swift Struct 不符合 Equatable 协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使结构符合Equatable"协议?

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

我使用的是 Xcode 7.3.1

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

}

当我使用MyStruct"时,Xcode 显示错误:

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

MyStruct 不符合Equatable"协议

您有没有让 MyStruct 符合协议的想法?

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

推荐答案

好的,经过大量搜索,它起作用了...

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
}

我的 Struct 在一个类中,所以它不起作用..我把这个 Struct 从我的类中移出,现在它很好:)

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

这篇关于Swift Struct 不符合 Equatable 协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 12:56