I understand that
self.something
this is member value for that class. but what is
something.self
I understand that
self.something
this is member value for that class. but what is
something.self
Consider code like
JSONDecoder().decode(what, from: myJSONData)
What goes where I have what
? We have to tell the decoder what type of thing to expect to decode. Basically, what
is the name of a type — the name of a class, struct, or enum that conforms to Decodable.
But how to say the name of a type? Let's suppose that the type of thing you expect to decode is String. Then what do you say here?
JSONDecoder().decode(String, from: myJSONData) // error
No, you can't just say the name of a type out of the blue like that. This is how you do it:
JSONDecoder().decode(String.self, from: myJSONData)
What you're really passing here when you say String.self
is the metatype for String. And this example is exactly what it's for, i.e. when you need to pass a type as a parameter.
The declaration of this method signals this by using .Type
:
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
The expression T.Type
tells you that what you pass when you call this method should be Something.self
.