Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two Struct objects? [duplicate]

Tags:

ios

swift

I have two objects for the same struct class having different values. I need to compare these two objects whether they are equal or not. Please guide me through a proper solution.

struct CustomerInfo {
   var billAddressCity: String?

   init(a:String?){
      billAddressCity = a

  }
}

 /* init object */
 var obj1 =  CustomerInfo?
 var obj2 =  CustomerInfo?

 obj1 = CustomerInfo(a: "ONE")
 obj2 = CustomerInfo(a: "TWO")

 /*  I need to compare these two objects */

 if obj1 == obj2 {
     Print(equal values)
  }

This is not the answer Iam looking for, as it says i need to compare each and every values of fields manually, Compare two instances of an object in Swift

like image 688
Jan Avatar asked Sep 06 '17 12:09

Jan


2 Answers

In the Object Oriented World, generally, all Objects are unique to each other.

So, how I could compare two objects?

Your struct/class need to implement the Equatable Protocol which let you define how an object could be equal to another object of the same class/struct

Let's begin with this House struct:

struct House {
    var street: String
}

var houseA = House.init(street: "street A, n. 10")
var houseB = House.init(street: "street A, n. 10")

houseA == houseB // of course you can't

With the Equatable protocol you can implement the static func ==. Here you can define how two object of the same class could be equal when you use the operator ==.

In my example, two objects of the struct House could be equal when they have the same street:

struct House: Equatable {
    var street: String

    static func == (lhs: House, rhs: House) -> Bool {
        return lhs.street == rhs.street
    }
}  

var houseA = House.init(street: "street A, n. 10")
var houseB = House.init(street: "street A, n. 10")

houseA == houseB // now print true
like image 104
Giuseppe Sapienza Avatar answered Oct 11 '22 19:10

Giuseppe Sapienza


By conforming to Equatable:

struct CustomerInfo: Equatable {
    var billAddressCity: String?

    init(a:String?){
        billAddressCity = a
    }

    static func ==(lhs: CustomerInfo, rhs: CustomerInfo) -> Bool {
        return (lhs.billAddressCity == rhs.billAddressCity)
    }
}
like image 27
sCha Avatar answered Oct 11 '22 18:10

sCha