What’s .self, .Type and .Protocol? Understanding Swift Metatypes

type(of:) Dynamic Metatypes vs .self Static Metatypes
So type(of) returns the metatype of an object, but what happens if I don’t have an object? Xcode gives me a compiler error if I try to call create(blogType: TutorialBlogPost.Type)!

To make it short, the reason you can’t do that is the same reason why you can’t call myArray.append(String): String is the name of the type, not the value! To get a metatype as a value, you need to type the name of that type followed by .self.

If that sounds confusing, you can see it like this: Just like String is the type and “Hello World” is the value of an instance, String.Type is the type and String.self is the value of a metatype.

let intMetatype: Int.Type = Int.self  
//
let widget = createWidget(ofType: MyWidget.self)
tableView.register(MyTableViewCell.self, forReuseIdentifier: "myCell")

.self is what Apple calls a static metatype - a fancy word for what is the compile time type of an object. You use that more than you expect - remember when I told you to ignore SwiftRocks.author? The reason was because writing that is the same as writing SwiftRocks.self.author.

继续阅读