250x250
반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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 31
Archives
Today
Total
관리 메뉴

개발자 수니

[iOS/Swift/Basic] 열거형 Enumerations : 비교 가능한 열거형 - Comparable 본문

iOS - Swift

[iOS/Swift/Basic] 열거형 Enumerations : 비교 가능한 열거형 - Comparable

개발자 수니 2024. 1. 26. 21:17
728x90
반응형

📑 이전글

[iOS/Swift/Basic] 열거형 Enumerations : 원시값 Raw Values, 연관값 Associated Values

[iOS/Swift/Basic] 열거형 Enumerations : 항목 순회 - CaseIterable

[iOS/Swift/Basic] 열거형 Enumerations : 순환 열거형 - indirect

 

Comparable 

  • Swift 프로그래밍 언어에서 제공하는 프로토콜
  • 이 프로토콜을 채택하면 연관 값(Associated Values)만 갖거나 연관 값(Associated Values)이 없는 열거형(Enumerations)은 각 케이스를 비교할 수 있다.
  • 앞에 위치한 케이스가 더 작은 값

 

연관 값(Associated Values)이 없는 예제

enum AppleDevice: Comparable {
    case iPhone
    case iPad
    case macBook
    case iMac
}

let myDevice: AppleDevice = .iMac
let yourDevice: AppleDevice = .iPhone

if myDevice > yourDevice {
    print("제 디바이스가 더 크네요!")
} else if myDevice < yourDevice {
    print("당신의 디바이스가 더 크네요!")
} else {
    print("우리 디바이스가 같네요!")
}
// 제 디바이스가 더 크네요!

 

연관 값(Associated Values)만 갖는 예제

enum AppleDevice: Comparable {
    case iPhone(version: String)
    case iPad(version: String)
    case macBook
    case iMac
}

var devices: [AppleDevice] = []
devices.append(.iMac)
devices.append(.iPhone(version: "6.1"))
devices.append(.iPhone(version: "14.3"))
devices.append(.iPad(version: "10.3"))
devices.append(.macBook)

let sortedDevices: [AppleDevice] = devices.sorted()
print(sortedDevices)
// [AppleDevice.iPhone(version: "14.3"), AppleDevice.iPhone(version: "6.1"), AppleDevice.iPad(version: "10.3"), AppleDevice.macBook, AppleDevice.iMac]

 

 

 

🙋🏻‍♀️ 참고

야곰, ⌜스위프트 프로그래밍: Swift5⌟, 한빛미디어(2019)

728x90
반응형
Comments