Link
Notice
HIT해
[Swift 기초문법 - 65] Any switch case let 본문
728x90
Any switch case let
Any 타입을 switch 문으로 알아내려할 때 case let을 활용하면 타입과 값 모두 알아낼 수 있다.
기본적인 사용예시
var things = [Any]()
struct Pet {
var name : String
}
struct Friend {
var name: String
}
things.append (0)
things.append (42)
things.append (Friend(name: "자우림"))
things.append ( (3.0, 5.0))
things.append(Pet (name: "댕댕이"))
things.append ({ (name:String) -> String in "난\(name)라고 해!" })
// any 타입의 배열을 스위치 문으로 처리 가능합니다
for thing in things {
switch thing {
case 0 as Int:
print ("0이 들어왔다")
case let somelnt as Int where somelnt > 10:
print ("someInt \(somelnt)는 10보다 크다")
case is Friend: // 자료형이 친구 라면
print ("들어온 게 친구 이다")
case let someString as String:
print("a string value of \"\(someString)\"")
case let (x, y) as (Double, Double):
print ("an (x, y) point at \(x), \(y)")
case let myDog as Pet:
print ("우리집 강아지 : (myDog.name)")
case let sayHi as (String) -> String:
print (sayHi("세밧흐촨"))
default:
print ("디폴트")
}
}
위와 같이 caselet 을 사용하면 타입과 값을 함께 추출할 수 있다.
주의할 점
- 타입 체크는 위에서 아래로 진행되므로, 구체적인 타입을 먼저 검사하는 것이 좋다. 예를 들어 AnyObject 타입을 검사하기 전에 더 구체적인 클래스 타입을 검사해야한다.
'Swift > 기초문법' 카테고리의 다른 글
[Swift 기초문법 - 67] allSatisfy (0) | 2024.08.22 |
---|---|
[Swift 기초문법 - 66] defer (0) | 2024.08.21 |
[Swift 기초문법 - 64] case let 옵셔널 패턴 (0) | 2024.08.21 |
[Swift 기초문법 - 63] 값을 동반한 enum (0) | 2024.08.21 |
[Swift 기초문법 - 62] Enum CaseIterable (0) | 2024.08.21 |