Notice
Recent Posts
Recent Comments
Link
«   2025/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
Tags
more
Archives
Today
Total
관리 메뉴

Olive Study Room

[Swift] RawRepresentable 본문

Coding/iOS

[Swift] RawRepresentable

Olive Dev 2021. 5. 1. 21:50

https://www.raywenderlich.com/4363809-uisearchcontroller-tutorial-getting-started

Candy struct의 Category가 RawRepresentable 프로토콜을 채택했는데 어떤 프로토콜일까?

 

먼저, raw value(원시값)이란?

 

Raw values

  • enum(열거형) 사용 시 swift에서는 case에 자동으로 정수값이 할당되지 않고(category를 예를 들면 all에는 0, chocolate에는 1이 자동 할당되지 않는다는 의미), case이름이 raw value가 된다.
  • String, Character, Int 타입만 가능하다 -> 자료형마다 원시값 규칙 존재 (string: case 이름과 동일/Charater: 직접 할당해줘야만 함/Int: 0, 1.. 순서대로 할당됨)
  • 필수로 지정해주지 않아도 된다.
enum month: Int{
    case Jan
    case Fab
    case Mar
    case Apr
    case May
    case Jun
}
month.Jan.rawValue // 0
month.Jun.rawValue // 5

 

Associated Values

  • 열거형 case에 원시값(raw value)을 저장하는 대신 연관된 값을 저장할 수도 있다.
  • case casename(Type, Type) 과 같이 사용한다.
  • 주로 switch-case 문으로 사용한다.
enum fruit {
    case apple(num: Int, color: String) // named tuple
    case grape(price: Int, size: String) // named tuple
    case mango(String, Int, Int) // unnamed tuple
    case peach(String, Int, Int) // unnamed tuple
}

switch appleBox {
case .apple(num: 10, color: "red"):
    print("Red apple, 10 boxes")
case .apple(num: 10, color: "green"):
    print("Green apple, 10 boxes")
case .apple(num: 100, color: "red"):
    print("Red apple, 100 boxes")
case .apple(num: 100, color: "green"):
    print("Green apple, 100 boxes")
case .grape(price: 100, size: "large"):
    print("100$, large grape")
case .mango:
    print("sold out")
case .peach:
    print("sold out")
} 

var appleBox = fruit.apple(num: 100, color: "green") // Green apple, 100 boxes

Option Sets

비트들의 집합. 비트들이 옵션을 나타내고, 이것의 집합을 비트로 나타낸 것.

Option sets은 OprionSet프로토콜을 사용하여 상속을 통해 RawRepresentable을 준수한다. Option set을 쓰든 직접 생성한 것을 쓰든, option set 인스턴스의 원시값을 사용하여 인스턴스의 비트 필드(rawValue: 1 << 0// 쉬프트 연산은 나중에... )를 저장해야한다. 따라서 원시 값은 UInt8이나 Int와 같은 FixedWidthInteger 프로토콜을 준수하는 타입이어야 한다. 예를 들어, Direction 타입은 게임에서 움직일 수 있는 네 가지 방향의 option set을 정의한다.

struct Directions: OptionSet {
    let rawValue: UInt8

    static let up    = Directions(rawValue: 1 << 0)
    static let down  = Directions(rawValue: 1 << 1)
    static let left  = Directions(rawValue: 1 << 2)
    static let right = Directions(rawValue: 1 << 3)
}

 

 

 

protocol  rawRepresentable

연결된 원시 값으로 변환하거나 원시 값에서 변환할 수 있는 유형

RawRepresentable 타입을 사용하면 본래의 RawRepresentable 타입을 손실하지 않고 커스텀 타입과 연관값(associated RawValue)타입간에 전환할 수 있다. 준수하는 타입의 원시 값을 사용하면 Objective-C나 legacy APIs와의 연동을 능률화하고 Equatable, Comparable 그리고 Hashable와 같은 다른 프로토콜과의 일치를 단순화한다.

 

RawRepresentable 프로토콜은 주로 원시 값과 옵션 set을 포함하는 열거형이라는 두가지 유형의 범주로 표시된다.

Comments