yoogail105 / KkokkoSwift

꼬리에 꼬리를 무는 swift 개념 정리
28 stars 0 forks source link

Equatable Example #80

Open yoogail105 opened 1 year ago

yoogail105 commented 1 year ago

Equatable Example

CustomColor라는 구조체를 만들어 보자.

struct CustomColor: Equatable {
    let red: Double
    let green: Double
    let blue: Double
}

위의 CustomColorEquatable을 채택했기 때문에 두 개의 값을 비교할 수 있다.

let color1 = CustomColor(red: 1.0, green: 0.5, blue: 0.0)
let color2 = CustomColor(red: 1.0, green: 0.5, blue: 0.0)

if color1 == color2 {
    print("The two colors are the same.")
} else {
    print("The two colors are different.")
}

바로 요런식으로!

yoogail105 commented 1 year ago

Equatable 특정 프로퍼티만 비교하기

위의 예제에서는 무조건 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이라는 프로토콜의 정체성에 어긋나는 일이 될 수 있다. 그렇기 때문에 이렇게 ==를 구현하여 특정 프로퍼티만을 비교하는 것은 반드시 주의해서 사용해야 한다.🍫