Compare two instances of an object in Swift
You could loop through fields by using keypath
I haven't tested this, but the general idea is there. Give a list of valid fields and loop through them instead of writing every single equatable. So it's the same as @duncan-c suggested but with looping.
Something like:
class PLClient:Equatable {
var name = String()
var id = String()
var email = String()
var mobile = String()
var companyId = String()
var companyName = String()
public static func ==(lhs: PLClient, rhs: PLClient) -> Bool{
let keys:[KeyPath<PLClient, String>] = [\.name, \.id, \.email, \.mobile, \.companyId, \.companyName]
return keys.allSatisfy { lhs[keyPath: $0] == rhs[keyPath: $0] }
}
}
Working off of Duncan C's answer, I have come up with an alternative which is slightly clearer that it is being used in a custom way:
// 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.")
}
Indicate that your class conforms to the Equatable protocol, and then implement the == operator.
Something like this:
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
}
}