이번에는 타입캐스팅에 대해 작성하고자 한다.
우선 스위프트는 다른 언어에 비해 다른 타입끼리의 값 교환을 엄격히 제한함
타입캐스팅
인스턴스의 타입을 확인하거나 자신을 다른 타입의 인스턴스인양 행세할 수 있는 방법으로 사용가능
자식 클래스는 부모클래스인 척을 할 수 있음 → 부모 클래스의 특성을 가지고 있기 때문
데이터 타입 확인 is
let myCoffee: Americano
let yourCoffee: Latte
coffee is Coffee //true
coffee is Americano //false
coffee is Latte //false
myCoffee is Coffee //true
myCoffee is Americano //true
myCoffee is Latte //false
yourCoffee is Latte //true
다운캐스팅
타입캐스트 연산자 as?!
let actingConstant: Coffee = Latte(flavor: "vanilla", shot: 2)
if let actingOne: Americano = coffee as? Americano {
print("This is Americano")
} else {
print(coffee.description)
}
//1 shot(s) coffee
if let actingOne: Americano = myCoffee as? Americano {
print("This is Americano")
} else {
print(coffee.description)
}
//This is Americano
Any, AnyObject의 타입캐스팅
func checkType(of item: AnyObject) {
if item is Latte {
print("item is Latte")
} else {
print("Unknown Type")
}
checkType(of: coffee) //Unknown Type
checkType(of: yourCoffee) //item is Latte
오랜만에 공부하니 좀 어색한 것 같다.. 후다닥 1회독을 해야겠다.
[출처] 스위프트 프로그래밍 (야곰), 야곰의 스위프트 기초문법 강좌, 개발하는 정대리 스위프트 강좌