Compare two instances of an object in Swift

Related searches

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.

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

Compare two instances of an object in Swift, Often we create custom classes like Person or Address and then need to compare if the two instances of this class or Objects are equal. With this Swift code� Swift 5.0 Published on 30 Mar 2017 The === operator lets you check if two objects are the same instance. Very useful when verifying that an array contains an instance in a test:

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

Comparable. Compare Custom Objects in Swift., In comparison, === is the identity operator, which checks whether two instances of a class point to the same memory. This is different from equality, because two objects that were created independently using the same values� === is the identical to operator and is used to test whether two object references both refer to the same object instance. It can be applied only to reference types (i.e. instances of a class). === is different from the "equal to" operator == (which is required in the Equatable protocol). Therefore, assuming that

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

What's the difference between == and ===?, As a part of summary I would say making comparison and equality logic as a part of Equatable protocol allows us to separate these two pieces of� Compare Custom Objects in Swift. Often we create custom classes like Person or Address and then need to compare if the two instances of this class or Objects are equal. With this Swift code example I would like to share with you how to compare two objects of a custom class you create by making a custom class conform to a Comparable protocol.

Equality and Comparison with custom objects in Swift (Equatable , This is useful since you can directly use array.contains(element) method to check the existence of element in an array without having to compare objects manually. Every time you execute array.contains([custom object]) , the static operator function for == is called and it internally checks if array already has custom object by performing

Swift is an inherited language from C and Objective-C, it is both a procedural language, both as a object oriented language. Class is a concept of the object-oriented programming language. Class have properties and methods, naturally, method is understood as a function of the class. From class you can create objects.

Section 7.10.7 of C# Programming Language (A. Hejlsberg, et. al, 2011 Fourth Edition, Annotated for 4.0 ) states that, ' When two separate string instances contain the exact same sequences of characters, the values of the strings are equal, but the references are different.' Is this ever the run-t

Comments
  • Overload == for you class.
  • By conforming to Equatable
  • is there a case to write a comparitor method with the equivalent signature of "isEqualTo:" ?
  • In Swift, the correct way to implement an equality test is a class or struct is to have it conform to the Equatable protocol. I can't see any reason to implement a function such as "isEqualTo:" particularly since the class could later be extended to conform to the Equality protocol and then have two potentially different equality tests. In addition, an "isEqualTo:" method could be overridden by a subclass. That would be a Bad Thing because it breaks the "Subclass of A is an A" rule. The Equality protocol == function cannot be overridden by a subclass.
  • Overall I have to disagree with this advice. The equatable protocol is intended for allowing objects to be compared for equality. By making a class conform to the equatable protocol, you are using the standard method for comparison. Using a custom "isEqualTo" method is non-standard, and makes things less clear, not more.