Swift
는 Type
에 민감한 언어이기 때문에 특정하지 않은 타입에 대해 동작하도록 특별한 타입 두 가지를 제공한다.Any 혹은 AnyObject 타입
을 사용할 경우, 상속 관계에 있지 않아도 타입 캐스팅이 가능하다.매번 타입 체크, 형 변환을 해야하므로 필요하지 않으면 사용하지 않아야 한다.
as를 이용
as? as!를 이용한 다운 캐스팅
var name: Any = "Derrick"
위와 같이 String 타입을 Any타입으로 선언하여도 name을 String 메서드나 프로퍼티에 접근하려하면 에러가 난다.
if var name = name as? String {
name = "김태현"
}