Open yoogail105 opened 1 year ago
위의 예제에서는 무조건 red, green, blue가 모두 같을 때에만 같다
고 판단한다.
하지만 만약에 red만 같아도 같다
고 판단하고 싶을 때에는 어떻게 해야할까?
무조건 struct 내의 모든 값이 같아야만 할까?
struct CustomColor: Equatable {
let red: Double
let green: Double
let blue: Double
static func ==(lhs: CustomColor, rhs: CustomColor) -> Bool {
return lhs.red == rhs.red
}
}
위처럼 static func ==(lhs: CustomColor, rhs: CustomColor) -> Bool
을 통해서 내가 규칙을 정할 수 있다.
하지만 이렇게 특정 프로퍼티만을 기준으로 동일성을 판단하는 것은,
Equatable
이라는 프로토콜의 정체성에 어긋나는 일이 될 수 있다.
그렇기 때문에 이렇게 ==
를 구현하여 특정 프로퍼티만을 비교하는 것은
반드시 주의해서 사용해야 한다.🍫
Equatable Example
CustomColor
라는 구조체를 만들어 보자.위의
CustomColor
는Equatable
을 채택했기 때문에 두 개의 값을 비교할 수 있다.바로 요런식으로!