Compare two instances of an object in Swift

Given the following class, how can you compare all values ​​in duplicate with 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.") } 

An example of a use for this is in an application that presents data from a server. After converting the data to an object, a copy of the object is created. The user can edit various fields, etc., which changes the values ​​in one of the objects.

The main object that may have been updated must be compared with a copy of this object. If the objects are equal (the values ​​of all properties are the same), nothing happens. If any of the values ​​is not equal, then the application sends the changes to the server.

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

+5
source share
2 answers

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

Something like that:

 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 } } 
+23
source

Disabling the Duncan C response, I came up with an alternative that is a little clearer that it is used in its own 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.") } 
+5
source

All Articles