타입 캐스팅 ( Type Casting )
표현식 is Type
<예제 코드1>
let char: Character = "A"
char is Character // true
char is String // false
let bool: Bool = true
bool is Bool // true
bool is Character // false
<예제 코드2>
class Human { }
class Teacher: Human { }
let teacher: Teacher = .init()
teacher is Teacher // true
teacher is Human // true
Human 클래스를 Teacher 이란 클래스가 "상속" 받을 경우, teacher 이라는 인스턴스는 Human 클래스의 서브 클래스이기 때문에 Human으로 타입 체크를 해도 true가 됨
class Human {
let name: String
init(name: String) {
self.name = name
}
}
class Teacher: Human { }
class Student: Human { }
let people: [Human] = [
Teacher.init(name: "김선생"),
Student.init(name: "박제자"),
Student.init(name: "유제자")
]
class Animal { }
class Dog: Animal { }
class Cat: Animal { }
if let dog = pet as? Dog {
print("Successfully casted to Dog.")
} else {
print("Failed to cast to Dog.")
}