macOS, iOS

struct, class instance 두개를 ==(등호)로 비교하고 싶다면?

SweetDev 2019. 10. 17. 20:10

https://stackoverflow.com/questions/46074718/how-to-compare-two-struct-objects

 

How to compare two Struct objects?

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 CustomerI...

stackoverflow.com

 

1. struct를 ==으로 비교할 수 있을까?

2. struct 내 값들이 모두 동일하다면, ==으로 비교한 값이 true일까?

 

아예 비교도 할 수 없다고 나온다 ㅠㅠ

나는 ==을 쓰고 싶은걸?!

 

 

 

 

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

'Equatable' 을 써줘야만 가능하다!!

 

기본적으로 OOP에서는 모든 객체는 unique해서, 비교를 하려면 무조건 equatable을 채택해야 한다. 

Equatable을 채택하고, == 함수의 내부를 내가 구현해주면 된다. 

 

 

 

class도 똑같이 Equatable 프로토콜을 써주면 된다 :D