比较Swift中一个对象的两个实例 [英] Compare two instances of an object in Swift

查看:123
本文介绍了比较Swift中一个对象的两个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下类,如何将两个实例中的所有值相互比较?

Given the following class, how can all the values in two instances be compared to each other?

// 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.")
}

用例在应用程序中,该应用程序显示来自服务器的数据。一旦将数据转换为对象,便会创建该对象的副本。用户可以编辑各种字段等,从而更改对象之一的值。

The use-case for this is in an application which presents data from a server. Once the data is converted into an object, a copy of the object is made. The user is able to edit various fields etc.. which changes the values in one of the objects.

可能需要更新的主要对象需要进行比较到该对象的副本。如果对象相等(所有属性的值都相同),则不会发生任何事情。如果任何值都不相等,则应用程序将更改提交给服务器。

The main object, which may have been updated, needs to be compared to the copy of that object. If the objects are equal (the values of all properties are the same) then nothing happens. If any of the values are not equal then the application submits the changes to the server.

如代码示例所示, == 运算符不被接受,因为未指定值。使用 === 不会获得所需的结果,因为它们始终是两个单独的实例。

As is shown in the code sample, the == operator is not accepted because a value is not specified. Using === will not achieve the desired result because these will always be two separate instances.

推荐答案

指示您的类符合Equatable协议,然后实现==运算符。

Indicate that your class conforms to the Equatable protocol, and then implement the == operator.

类似这样的东西:

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

这篇关于比较Swift中一个对象的两个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆