본문 바로가기
Development

A Swift Tour: Enumerations and Structures

by Dev Arthur 2023. 7. 20.
  • Use enum to create an enumeration. Like classes and all other named types, enumerations can have methods associated with them.
    = 'enum'을 사용해 열거형을 만들고, 클래스들이나 모든 다른 명명된 타입들 처럼 열거형은 메소드를 가질 수 있다
  • ex)
enum Rank: Int {
    case ace = 1
    case two, three, four, five, six, seven, eight, nine, ten
    case jack, queen, king


    func simpleDescription() -> String {
        switch self {
        case .ace:
            return "ace"
        case .jack:
            return "jack"
        case .queen:
            return "queen"
        case .king:
            return "king"
        default:
            return String(self.rawValue)
        }
    }
}
let ace = Rank.ace
let aceRawValue = ace.rawValue


func rankCompare(_ ARank: Rank,_ BRank: Rank) -> (){
    if (ARank.rawValue > BRank.rawValue){
        print("ARank Win")
    }
    else if (BRank.rawValue > ARank.rawValue){
        print("BRank Win")
    }
    else{
        print("Draw")
    }
}
  • By default, Swift assigns the raw values starting at zero and incrementing by one each time, but you can change this behavior by explicitly specifying values.
    = 기본적으로 Swift는 원시값을 0부터 시작하고 매 순간마다 1씩 증가하지만, 명시적으로 값을 지정해서 이 동작을 바꿀 수 있다
  • In the example above, Ace is explicitly given a raw value of 1, and the rest of the raw values are assigned in order.
    = 위 예시에서는 Ace는 명시적으로 원시값이 1이 주어졌고 나머지 원시값들은 순서대로 (1씩 증가하며) 부여된다
  • You can also use strings or floating-point numbers as the raw type of an enumeration.
    = 열거형의 원시값 타입으로 문자열이나 소수점 숫자을 사용할 수도 있다
    * 문자열을 원시값 타입으로 사용할 경우, 원시값을 지정하지 않을 경우 클래스의 이름이 원시값이 된다
  • Use the rawValue property to access the raw value of an enumeration case.
    = 열거형 케이스의 원시값에 접근하기 위해 'rawValue' 프로퍼티를 사용한다
  • Use the init?(rawValue:) initializer to make an instance of an enumeration from a raw value.
    = 원시값으로 열거형 인스턴스를 만들기 위해서 'init?(rawValue:)' 초기화 구문을 사용한다
  • It returns either the enumeration case matching the raw value or nil if there’s no matching Rank(my enum).
    = ('init?(rawValue:)' 초기화 구문은) 원시값과 맞는 열거형 케이스를 반환하거나, 내 열거형에 일치하는게 없다면 nil을 반환한다
  • ex)
if let convertedRank = Rank(rawValue: 3) { //해당 열거형에 원시값 3인 케이스가 있다면 그 케이스를 반환, 없다면 nil
    let threeDescription = convertedRank.simpleDescription()
}
  • The case values of an enumeration are actual values, not just another way of writing their raw values.
    = 열거형 케이스의 값은 (그 케이스의) 원시값을 적는 또 다른 방법이 아니라 실제 값이다
  • In fact, in cases where there isn’t a meaningful raw value, you don’t have to provide one.
    = 실제로, 의미있는 원시값이 없는 케이스는 (원시값을) 제공할 필요 없다
  • ex)
enum Suit { //원시값이 필요없는 경우 열거형의 타입 생략(?)
    case spades, hearts, diamonds, clubs 

    func simpleDescription() -> String {
        switch self {
        case .spades:
            return "spades"
        case .hearts:
            return "hearts"
        case .diamonds:
            return "diamonds"
        case .clubs:
            return "clubs"
        }
    }
    
    func color() -> String{
        switch self{
        case .spades, .clubs:
            return "black"
        case .diamonds, .hearts:
            return "red"
        }
    }
}
let hearts = Suit.hearts
let heartsDescription = hearts.simpleDescription()
let heartsColor = hearts.color()
  • Notice the two ways that the hearts case of the enumeration is referred to above:
    = 위 예시에서 열거형의 'hearts' 케이스가 참조되는 2가지 방법
    1. When assigning a value to the 
    hearts constant, the enumeration case Suit.hearts is referred to by its full name because the constant doesn’t have an explicit type specified.
    = 'hearts' 상수에 값을 할당할 때, ('hearts'의) 상수는 지정된 명시적 타입이 없기 때문에 열거형 케이스 'Suit.hearts'는 그 풀네임으로 참조된다
    2. Inside the switch, the enumeration case is referred to by the abbreviated form .hearts because the value of self is already known to be a suit.
    You can use the abbreviated form anytime the value’s type is already known.
    = 스위치 문 내부에서, 열거형 케이스는 'self'의 값을 이미 Suit로 알고 있기 때문에 열거형 케이스는 축약형으로 참조된다
    값의 타입이 이미 알려져있을 때는 언제나 축약형으로 쓸 수 있다
  • If an enumeration has raw values, those values are determined as part of the declaration, which means every instance of a particular enumeration case always has the same raw value.
    = 만약 열거형이 원시값을 갖고있다면, (그 열거형 케이스의) 값들은 선언될 때 결정되는데 이건 특정 열거형 케이스(원시값을 갖는?)의 모든 인스턴스는 항상 같은 원시값을 가진다는 것을 의미한다
  • Another choice for enumeration cases is to have values associated with the case — these values are determined when you make the instance, and they can be different for each instance of an enumeration case.
    = 열거형 케이스의 또 다른 선택은 그 케이스와 관련된 값을 갖는 것이다 - 이러한 값들은 (그 케이스의) 인스턴스가 만들어 질 때 결정되고 각각의 열거형 케이스의 인스턴스는 다를 수 있다
  • You can think of the associated values as behaving like stored properties of the enumeration case instance.
    = 관련된 값들(케이스와 관련된 값을 갖는 값)은 그러한 열거형 케이스의 인스턴스의 저장된 프로퍼티처럼 작동한다고 생각할 수 있다
  • For example, consider the case of requesting the sunrise and sunset times from a server.
    = 서버로 부터 일출과 일몰의 시간을 요청받는 상황을 가정해보자
  • The server either responds with the requested information, or it responds with a description of what went wrong.
    = 서버는 요청된 정보에 대해 응답하거나, 무엇이 잘못 되었는지에 대해 설명을 응답한다
  • ex)
enum ServerResponse {
    case result(String, String)
    case failure(String)
    case pause(String)
}


let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")
let pause = ServerResponse.pause("Waiting Restart")


switch failure {
case let .result(sunrise, sunset):
    print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
    print("Failure...  \(message)")
case let .pause(message):
    print("Pause...  \(message)")
}
  • Use struct to create a structure.
    'struct'를 사용해서 구조체를 만든다
  • Structures support many of the same behaviors as classes, including methods and initializers.
    = 구조체는 메소드와 초기화 구문을 포함해서 클래스처럼 작동하는 것을 지원한다
  • One of the most important differences between structures and classes is that structures are always copied when they’re passed around in your code, but classes are passed by reference.
    =구조체와 클래스의 가장 중요한 차이점 중 하나는 구조체는 코드에서 전달될 때 항상 복제되지만, 클래스는 참조된다
  • ex)
struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() -> String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }
}

let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()

func Deck() -> [Card]{
    var Decks = [Card]()
    var suits : [Suit] = [.spades,.diamonds,.hearts,.clubs]
    var ranks : [Rank] = [.ace,.two,.three,.four,.five,.six,.seven,.eight,.nine,.ten,.jack,.queen,.king]
    
    for suit in suits{
        for rank in ranks {
            Decks.append(Card(rank: rank, suit: suit))
        }
    }
    return Decks
}

Deck().forEach({ Card in
    print(Card.simpleDescription())
})
반응형

'Development' 카테고리의 다른 글

CocoaPods 설치하기  (0) 2024.02.16
Homebrew 설치하기  (0) 2024.02.15
A Swift Tour: Objects and Classes  (0) 2023.07.13
A Swift Tour: Functions and Closures  (0) 2023.04.25
Xcode 설치하기  (0) 2023.04.13