Answer the question
In order to leave comments, you need to log in
What do A.Type and A.self, where A is a class, mean in Swift?
What do A.Type and A.self mean, where A is some class, in Swift language?
Answer the question
In order to leave comments, you need to log in
For any type T
, T.Type
is a metatype, that is, a type whose objects provide a description of the type T
. Static functions and init
-functions T
become member functions T.Type
. Example:
struct Duck {
static func kind() -> String { return "Bird" }
init() { }
func talk() { print("Quack") }
}
let meta: Duck.Type = Duck.self
meta.kind() //=> Bird
let obj: Duck = meta.init()
obj.talk() //=> Quack
T
and any successor (subtype) of the type T
. In other words, the set of type objects T.Type
is U.self
for all types U: T
. Example:class Animal { class var name: String { return "Animal" } }
class Cat: Animal { override class var name: String { return "Cat" } }
class Dog: Animal { override class var name: String { return "Dog" } }
var meta: Animal.Type
meta = Cat.self
meta.name //=> Cat
meta = Dog.self
meta.name //=> Dog
class Animal { ... }
func createAnimal(_ type: Animal.Type) -> Animal {
if type == Cat.self {
return Cat(...)
} else if type == Dog.self {
return Dog(...)
} else {
fatalError()
}
}
U.Type
, since the U
function does not accept type arguments. Rather, this is the best and accepted way in Swift. It would be possible to get out like this: unsafeCast<U>(t)
at a call. U.Type
in this way, its value is generally ignored. That is, even if you pass the metatype of the heir of type U there, the function will still work with U.Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question