티스토리 뷰

Tech/iOS

Equatable 프로토콜

Ellie Kim 2020. 5. 3. 22:32

https://developer.apple.com/documentation/swift/equatable

스위프트 표준 라이브러리의 대부분의 데이터 타입은 Equatable프로토콜을 준수합니다.

Equatable 프로토콜은 == 를 사용해 같은지 비교할 수 있습니다.

또 != 를 사용해서 다른지 비교할 수 있습니다.

 

아래 코드는 Kofi가 students배열["Kofi", "Abena", "Efua", "Kweku", "Akosua"]에 포함되어 있는지 확인하는 작업입니다.

let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]

let nameToCheck = "Kofi"

if students.contains(nameToCheck) {
    print("\(nameToCheck) is signed up!")
} else {
    print("No record of \(nameToCheck).")
}
// Prints "Kofi is signed up!"

 

contains를 활용해 students의 element를 하나씩 가져와 nameToCheck변수와 비교하는 작업을 해줍니다.

(contains는 주어진 element가 시퀀스에 포함되는지 안되는지 확인해 Boolean 값을 리턴해줍니다.)

 

그럼 이 Equatable 프로토콜을 언제 사용해야 할까요?

 

Equatable 프로토콜은 Hashable, Comparable프로토콜의 기반이 됩니다.

custom 타입일 때 사용하면 좋습니다.

  • 구조체에서 프로퍼티 정렬 때 Equatable을 준수
  • 열거형에서 연관 값 쓸 때 Equatable을 준수
class StreetAddress {
    let number: String
    let street: String
    let unit: String?

    init(_ number: String, _ street: String, unit: String? = nil) {
        self.number = number
        self.street = street
        self.unit = unit
    }
}

extension StreetAddress: Equatable {
    static func == (lhs: StreetAddress, rhs: StreetAddress) -> Bool {
        return
            lhs.number == rhs.number &&
            lhs.street == rhs.street &&
            lhs.unit == rhs.unit
    }
}

StreetAddress는 Equatable을 준수합니다.

Equatable 프로토콜에는 무조건 구현해야 하는 함수가 존재합니다.

 

== 함수를 통해 같음을 정의해줍니다.

let addresses = [StreetAddress("1490", "Grove Street"),
                 StreetAddress("2119", "Maple Avenue"),
                 StreetAddress("1400", "16th Street")]
let home = StreetAddress("1400", "16th Street")

print(addresses[0] == home)
// Prints "false"
print(addresses.contains(home))
// Prints "true"

이로 인해 동등함을 비교할 수 있게 됩니다.

 

  • static func == (Self, Self) -> Bool
  • static func != (Self, Self) -> Bool

이는 필수 구현돼야 하는 함수입니다.

 

또 다른 예를 봅시다. 

만약에 a,b,c를 비교한다고 가정한다면 아래와 같습니다.

a==a 는 항상 같습니다.

a==b 는 b==a를 함축합니다.

a==b그리고 b==c는 a==c를 함축합니다.

하지만 a!=b라고 해서 !(a==b)라고 말할 순 없습니다.

 

IntegerRef는 정수를 감싸고 있습니다.

여기서 ==는 값이 같은가가 아닌 주소 값에 대한 비교가 들어갑니다.

이럴 땐 Equatable을 구현해줍니다.

class IntegerRef: Equatable {
    let value: Int
    init(_ value: Int) {
        self.value = value
    }

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

a, a 그리고 a, b가 같은지 확인합니다.

값이 같기 때문에 true, true가 출력됩니다.

let a = IntegerRef(100)
let b = IntegerRef(100)

print(a == a, a == b, separator: ", ")
// Prints "true, true"

c에 a의 참조값을 전달하면,

c===a는 동일하다고 판단합니다.

c===b는 동일한 참조 값이 아니니 false가 출력됩니다.

let c = a
print(c === a, c === b, separator: ", ")
// Prints "true, false"

=== 은 주소 값 비교입니다.

Equatable은 같은지 같지 않은지 판단할 수 있도록 해주는 프로토콜입니다.

 

https://developer.apple.com/documentation/swift/equatable

 

Equatable - Swift Standard Library | Apple Developer Documentation

Conforms when A conforms to Equatable, B conforms to Equatable, C conforms to Equatable, D conforms to Equatable, E conforms to Equatable, F conforms to Equatable, G conforms to Equatable, and H conforms to Equatable.

developer.apple.com

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함