Mic*_*ola 10 comparison class object swift
给定以下类,如何将两个实例中的所有值相互比较?
// 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.")
}
Run Code Online (Sandbox Code Playgroud)
用例是在一个从服务器提供数据的应用程序中.将数据转换为对象后,将生成对象的副本.用户能够编辑各种字段等,这些字段会更改其中一个对象中的值.
可能已更新的主要对象需要与该对象的副本进行比较.如果对象相等(所有属性的值相同),则没有任何反应.如果任何值不相等,则应用程序将更改提交给服务器.
如代码示例所示,==不接受运算符,因为未指定值.使用===不会达到预期的结果,因为它们总是两个独立的实例.
Dun*_*n C 35
指示您的类符合Equatable协议,然后实现==运算符.
像这样的东西:
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
}
}
Run Code Online (Sandbox Code Playgroud)
根据Duncan C的回答,我提出了一个替代方案,它更加清晰,以自定义方式使用:
// 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
}
func equals (compareTo:PLClient) -> Bool {
return
self.name == compareTo.name &&
self.email == compareTo.email &&
self.mobile == compareTo.mobile
}
}
var clientOne = PLClient()
var clientTwo = PLClient(copyFrom: clientOne)
if clientOne.equals(clientTwo) {
println("No changes made")
} else {
println("Changes made. Updating server.")
}
Run Code Online (Sandbox Code Playgroud)