티스토리 뷰


출처

http://kka7.tistory.com/10



열거형 (Enumerations)


Swift 의 enum 은 매우 유연하고 
열거형의 각 case 에 대한 값을 반드시 제공하지 않는다.

값들은 각 열거형 case 에 대해 제공되며
그 값은 문자열, 문자, 정수형, 실수형 타입이 될 수 있다.

또한 열거형은 그 자체로 클래스 타입이다.
열거형의 현재 값에 관해 추가정보를 제공하기 위해
프로퍼티나 관련된 함수를 제공하는 인스턴스 메소드 등을 사용할 수 있다.

열거형은 초기화를 정의할 수 있고
확장하기 위해 확장될 수 있다. 그리고 표준 기능을 제공하기 위해
프로토콜을 준수할 수 있다.



문법

enum CompassPoint {

    case north

    case south

    case east

    case west

}


Objective C 와 다르게 Swift 는 생성될 때 기본으로 정수형 값을 할당하지 않는다.

위 예제에서도 0, 1, 2, 3 이 아니다.

아래처럼 한줄로도 표현할 수 있다.


enum Planet {

    case mercury, venus, earth, mars,

    jupiter, saturn, uranus, neptune

}



사용시에는 짧은 ( . ) 문법을 사용한다.


var direction : CompassPoint

direction = .north




Switch 구문과 함께 쓰기

var direction : CompassPoint

direction = .south


switch direction {

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

}



열거형의 case 를 구성할 때, switch 구문은 완벽해야한다.

즉, 열거형의 경우 모든 케이스의 경우가 없다면

default 구문이 강제된다.





연관된 값 (Associate Values)

하나의 enum 안에 다른 타입과 관련된 값을 선언할 수 있다.

UPC 바코드와 QR 코드를 예제로 가져보자.

enum Barcode {

    case upc(Int, Int, Int, Int)

    case qrCode(String)

}


var product = Barcode.upc(8, 85909, 51226, 3)

product = .qrCode("ABCDEFG")


switch product {

case .upc(let numberSystem, let manufacturer, let product, let check):

    print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")

case .qrCode(let productCode):

    print("QR code: \(productCode).")

}


var 또는 let 을 case 뒤에 바로 두어 모든 parameter 에 있는

let 을 생략할 수 있다.


switch product {

case let .upc(numberSystem, manufacturer, product, check):

    print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")

case let .qrCode(productCode):

    print("QR code: \(productCode).")

}






원시 값 (Raw Values)

열거형 case 는 동일한 타입의 전부를
기본값으로 미리 채울 수 있다.

원시 값은 문자열, 문자, 정수형, 실수형 숫자 타입이 될 수 있다.
각 원시 값은 열거형 선언 내에서 고유해야한다.


enum ASCIIControlCharacter: Character {

    case tab = "\t"

    case lineFeed = "\n"

    case carriageReturn = "\r"

}



암시적인 원시값 할당

열거형에서 정수나 문자열 원시값을 저장할 때
각각의 case 에 대한 원시값을 명시적으로 설정할 필요가 없다.

설정하지 않으면, 자동으로 값에 대해서 할당해준다.

enum Planet: Int {

    case mercury = 1, venus, earth, mars,

    jupiter, saturn, uranus, neptune

}


print(Planet.venus.rawValue)


enum CompassPoint: String {

    case north, south, east, west

}


print (CompassPoint.north.rawValue)




원시 값으로 초기화

언제나 원시값이 열거형 case 를 반환하는 것이 아니기 때문에
원시값 초기화는 실패할 수 있는 초기화이다.
아래 예제에서 해당 rawValue 에 해당하는 case 값이 없을 수 있다.
이에, return 되는 값은 Optional 값이다.

let planet = Planet(rawValue: 2)

print(planet!)



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

    //Print

}




재귀 열거형 (Recursive Enumerations)

하나 이상의 열거형 case 와 연관된 값처럼
다른 열거형의 인스턴스를 가진다.

그 전에 indirect 로 작성된 열거형 case 는 재귀한다.
간접적인 필수 레이어를 추가하는 것을 컴파일러가 알려준다.

enum ArithmeticExpression {

    case number(Int)

    indirect case addition(ArithmeticExpression, ArithmeticExpression)

    indirect case multiplication(ArithmeticExpression, ArithmeticExpression)

}


필요한 경우 모든 열거형 case 에 대해 간접적으로 사용하기 위해 

열거형을 시작하기 전에 indirect 를 사용할 수도 있다.


indirect enum ArithmeticExpression {

    case number(Int)

    case addition(ArithmeticExpression, ArithmeticExpression)

    case multiplication(ArithmeticExpression, ArithmeticExpression)

}




( 5 + 4 ) * 2 를 재귀 열거형 표현식으로 구현해보면 아래와 같다.



let five = ArithmeticExpression.number(5)

let four = ArithmeticExpression.number(4)

let sum = ArithmeticExpression.addition(five, four)

let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))


func evaluate(_ expression: ArithmeticExpression) -> Int {

    switch expression {

    case let .number(value):

        return value

    case let .addition(left, right):

        return evaluate(left) + evaluate(right)

    case let .multiplication(left, right):

        return evaluate(left) * evaluate(right) }

}


print(evaluate(product))

// Prints "18"








공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   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
글 보관함