Reference
- 내용전반 : SwiftLanguageReference
- 내용전반 : 동동이 - Metatype
metatype 타입은 class/struct/enum/protocol 타입의 타입을 말합니다
🔘 .Type
/.Protocol
: 타입의 타입
class/struct/enum는 타입명 뒤에 .Type
을 붙이고, protocol은 프로토콜명 뒤에 .Protocol
을 붙입니다
(ex. SomeClass.Type / SomeProtocol.Protocol)
🔘 .self
: 타입의 타입의 값
위에서 설명한 .Type
/.Protocol
이 타입의 타입인 반면, .self
는 타입의 타입의 값입니다
(ex. SomeClass.self)
따라서, 파라미터로 넘긴다던지 등 값으로써 사용이 필요하다면
.self
를 사용해야 합니다
type(of:)
메서드를 사용하면 인스턴스로부터 타입을 추출할 수 있습니다
주의할 점으로, 이 메서드는 underlying이 아닌 해당 인스턴스의 dynamic/runtime 타입을 반환합니다
class SomeBaseClass {
class func printClassName() {
print("SomeBaseClass")
}
}
class SomeSubClass: SomeBaseClass {
override class func printClassName() {
print("SomeSubClass")
}
}
let someInstance: SomeBaseClass = SomeSubClass()
// The compile-time type of someInstance is SomeBaseClass,
// and the runtime type of someInstance is SomeSubClass
type(of: someInstance).printClassName()
// Prints "SomeSubClass"
class AnotherSubClass: SomeBaseClass {
let string: String
required init(string: String) {
self.string = string
}
override class func printClassName() {
print("AnotherSubClass")
}
}
let metatype: AnotherSubClass.Type = AnotherSubClass.self
let anotherInstance = metatype.init(string: "some string")
단, class 인스턴스에 대해서는 initializer에 required
를 붙이거나 final
class만 가능하다