给定以下类,如何将两个实例中的所有值相互比较?
// Client Object // class PLClient { var name = String() var id = String() var email = String() var mobile = String() var companyId = String() var companyName = String() convenience init (copyFrom: PLClient) { self.init() self.name = copyFrom.name self.email = copyFrom.email self.mobile = copyFrom.mobile self.companyId = copyFrom.companyId self.companyName = copyFrom.companyName } } var clientOne = PLClient() var clientTwo = PLClient(copyFrom: clientOne) if clientOne == clientTwo { // Binary operator "==" cannot be applied to two PLClient operands println("No changes made") } else { println("Changes made. Updating server.") }
用例是在一个从服务器提供数据的应用程序中.将数据转换为对象后,将生成对象的副本.用户能够编辑各种字段等,这些字段会更改其中一个对象中的值.
可能已更新的主要对象需要与该对象的副本进行比较.如果对象相等(所有属性的值相同),则没有任何反应.如果任何值不相等,则应用程序将更改提交给服务器.
如代码示例所示,不接受==运算符,因为未指定值.使用===将无法实现所需的结果,因为它们将始终是两个单独的实例.
指示您的类符合Equatable协议,然后实现==运算符.
原文链接:https://www.f2er.com/swift/319045.html像这样的东西:
class PLClient: Equatable { var name = String() var id = String() var email = String() var mobile = String() var companyId = String() var companyName = String() //The rest of your class code goes here public static func ==(lhs: PLClient,rhs: PLClient) -> Bool{ return lhs.name == rhs.name && lhs.id == rhs.id && lhs.email == rhs.email && lhs.mobile == rhs.mobile && lhs.companyId == rhs.companyId && lhs.companyName == rhs.companyName } }