Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- ReactNative
- LiveData
- class component
- function
- lifecycle
- MINUS
- animation
- AWS
- map
- Foreign Key
- list
- Interface
- recyclerview
- mongoose
- Service
- Kotlin
- Generic
- react native
- elementAt
- docker-compose
- union
- collection
- Filter
- enum
- CLASS
- vuex
- docker
- Swift
- ConstraintLayout
- 생명주기
Archives
- Today
- Total
개발 일기
Enumerations 본문
Emumerations
"enumeration"은 값에 대해서 연관된 공통적인 타입을 정의하고 type-safe 한 방식으로 다룰수 있게 만들어줍니다.
Swift은 C언어와는 달리 더 유연해서 값이 제공을 할수도 있고 안 할수도 있습니다.
제공이 된다면 문자 , 숫자 등 다양한 타입이 가능합니다.
Enumeration Syntax
아래와 같이 사용이 가능합니다.
enum CompassPoint {
case north
case south
case east
case west
}
만약에 한줄로 표시하고 싶은 경우에는 아래와 같이 가능합니다.
enum Planet {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
// Planet에서 mercury 가져옵니다.
var directionToHead = Planet.mercury
// Planet에서 가져온걸 유추할수 있기 때문에 .으로도 가져올수가 있습니다
directionToHead = .venus
print(directionToHead) // venus
Matching Enumeration Values with a Switch Statement
아래와 같이 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"
다음에는 아래와 같이 enum에 대해서 모든 경우에 수를 적지 않을 경우에는 에러가 발생합니다. 따라서 default문을 해주셔야합니다.
let somePlanet = Planet.earth
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
Iterating over Enumeration Cases
enum을 Iterating 하고 싶은 경우에는 아래와 같이 enum 이름 오른쪽에 "CaseIterable" protocol 을 사용하면 됩니다.
enum Beverage: CaseIterable {
case coffee, tea, juice
}
let numberOfChoices = Beverage.allCases.count
print("\(numberOfChoices) beverages available")
// Prints "3 beverages available"
for beverage in Beverage.allCases {
print(beverage)
}
// coffee
// tea
// juice
이 외에도 다양한 형식 예제
import Foundation
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
print("QR code: \(productCode).")
}
enum ASCIIControlCharacter: String {
case tab = "tab"
case lineFeed = "lineFeed"
case carriageReturn = "carriageReturn"
}
print(ASCIIControlCharacter.tab.rawValue)
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
print(ASCIIControlCharacter.tab.rawValue)
enum Planet: Int {
case mercury = 1, venus = 2, earth = 3, mars, jupiter, saturn, uranus, neptune
}
let positionToFind = 2
if let somePlanet = Planet(rawValue: 4) {
switch somePlanet {
case .mars:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
} else {
print("There isn't a planet at position \(positionToFind)")
}
마지막으로 재귀열거에 대해서 설명하도록 하겠습니다.
재귀 열거는 하나의 case에서 다른 Instance가 매개변수로 있는것을 말합니다.
이 경우에는 "indirect"을 통해서 해결을 할수가 있습니다.
// 부분적으로 활성화
enum ArithmeticExpression {
case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
// 전체 활성화
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
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)
}
}
'컴퓨터 언어 > swift' 카테고리의 다른 글
Closures ? (0) | 2020.05.17 |
---|---|
Function ? (0) | 2020.05.16 |
Control Flow ? (0) | 2020.05.10 |
Collection Type ? (0) | 2020.05.03 |
Strings and Characters (0) | 2020.05.01 |
Comments