티스토리 뷰

Mobile/iOS

swift. Type matching - 1. enum의 경우

out of coding 2019. 3. 23. 18:57

enum은 swift에서 사용하기에 가장 훌륭한 자료형입니다.

이것을 다양한 자료형을 이용하기 위해서 사용할 경우의 사용방법입니다.


1. 기본 대입 방법입니다.


다음과 같은 enum이 있다고 합시다.


1
2
3
4
5
enum CustomType {
    case string(_ value: String)
    case number(_ value: Int)
    case date(_ value: Date)
}
cs


그러면 이것을 이용하기 위한 방법은 여러가지 입니다.


1. switch를 이용


1
2
3
4
5
6
7
8
9
10
11
12
let type = CustomType.number(1)
 
func test() {
    switch type {
    case let .date(value):
        // value는 Date
    case .string(value):
        // value는 String
    case .number(value):
        // value는 Int
    }
}
cs


2. switch의 where를 이용


1
2
3
4
5
6
7
8
9
10
11
12
13
14
let type = CustomType.string("not")
 
func test() {
    switch type {
    case let .date(value):
        // value는 Date
    case .string(value) where value == "test" :
        // value는 String
    case .number(value):
        // value는 Int
    default:
        // 나머지 케이스. string이 test가 아닐 
    }
}
cs


3. switch에 바로 대입할 경우


1
2
3
4
5
6
7
8
9
10
11
12
13
14
let type = CustomType.number(1)
 
func test() {
    switch type {
    case let .date(value):
        // value는 Date
    case .string(value) where value == "test" :
        // value는 String
    case .number(1):
        // value가 1일 
    default:
        // 나머지 케이스. string이 test가 아닐 경우
    }
}
cs


4. switch에 두개의 타입일 경우


1
2
3
4
5
6
7
8
9
10
11
12
13
14
let type = CustomType.number(1)
 
func test() {
    switch type {
    case let .date(value):
        // value는 Date
    case .string(value) where value == "test" :
        // value는 String
    case .number(1), .number(2):
        // value가 1,2일 경우
    default:
        // 나머지 케이스. string이 test가 아닐 경우
    }
}
cs


'Mobile > iOS' 카테고리의 다른 글

swift. Type matching - 3. Custom aka. ~=  (0) 2019.03.23
swift. Type matching - 2. Type별  (0) 2019.03.23
swift. Codable의 변경사항. json snake to camel  (0) 2019.03.23
RxSwift. Hot, Cold Observe  (0) 2018.12.21
print, debugPrint  (0) 2018.12.10
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함