[swift] A Swift Tour -Enumerations and Structures

12209 단어 swift스위프트swift

📌 Apple의 공식 문서인 The Swift Programming Language (Swift 5.5)에서 A Swift Tour를 말 그대로 '재빨리 둘러보며' 정리한 포스트입니다.

📙Enumerations and Structures

📖Enumeration

📎Enum

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
  • method 가질 수 있음
  • 원시값은 0에서 시작해 1씩 증가(명시적으로 값 지정해서 변경 가능)
  • rawValue 속성을 통해 원시값에 접근

📎init?(rawValue:)

if let convertedRank = Rank(rawValue: 3) {
    let threeDescription = convertedRank.simpleDescription()
    print(threeDescription) //3
}
  • 원시값으로 열거체의 instance 생성
  • 원시값과 일치하는 case의 원시값을 반환, 일치하는 Rank가 없는 경우 nil을 반환

📎The case values of an enumeration

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"
        }
    }
}
let hearts = Suit.hearts
let heartsDescription = hearts.simpleDescription()
  • 각 case는 그 자체로 고유의 값
    → 원시값이 의미가 없는 경우, 원시값을 제공하지 않아도 됨
  • 값의 type을 안다면 switch문에서처럼 축약형으로 사용 가능

📎Associated values

원시값 : case의 모든 instance가 같은 값 가짐
→ 연관값으로 극복

enum ServerResponse {
    case result(String, String)
    case failure(String)
}

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

switch success {
case let .result(sunrise, sunset):
    print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
    print("Failure... \(message)")
} //Sunrise is at 6:00 am and sunset is at 8:09 pm.

📖Structure

➰class와 유사
가장 큰 차이점: class → call by reference, struct → call by value

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()

좋은 웹페이지 즐겨찾기