iOS & Swift

[Swift] Swift 공식문서 정리 - 4(열거형)

석지한 2022. 4. 6. 15:09
반응형

열거형이란 ?

- 같은 주제로 연관된 데이터들을 멤버로 구성하여 나타내는 자료형

 

열거형의 선언

enum CompassPoint {
    case north
    case south
    case east
    case west
}

var directionToHead = CompassPoint.west
// 이후엔 생략 가능
directionToHead = .east

 

Switch 구문에서 열거형의 사용

directionToHead = .south
switch directionToHead {
case .north:
    print("Lots of planets have a north")
case .south:
    print("Watch out for penguins")
case .east:
    print("Where the sun rises")
case .west:
    print("Where the skies are blue")
}
// Prints "Watch out for penguins"

 

RAW 값 사용

enum Planet: Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
} 

enum CompassPoint: String {
    case north, south, east, west
}

let earthsOrder = Planet.earth.rawValue
// earthsOrder is 3

let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"

 

 

RAW값을 이용한 초기화

let positionToFind = 11
if let somePlanet = Planet(rawValue: positionToFind) {
    switch somePlanet {
    case .earth:
        print("Mostly harmless")
    default:
        print("Not a safe place for humans")
    }
} else {
    print("There isn't a planet at position \(positionToFind)")
}
// Prints "There isn't a planet at position 11"

 

참고

https://babbab2.tistory.com/category/iOS/Swift

https://jusung.gitbook.io/the-swift-language-guide/

반응형