There are many features of the Swift language, one of which is the type method, compared to other popular programming languages (C #, Java), the most important feature of the type method in Swift is its inheritance, let's give an example:
As the saying goes, Dragonjet Phoenix born chicken mice will play holes, although the dragon and rats are animals, but after all, not the same, so the birth of course not the same.
Similarly, for Dragon and mouse two classes, the results of their newinstance type methods should be instances of their respective classes;
Let's start by creating a protocol named animal:
protocol Animal { -- Animal}
This protocol is simple and requires that all classes that implement it should define the Newinstance method:
class Dragon:animal, Printable { -= Animal {return Dragon () } = "Dragon"}class mouse:animal, Printable { - Animal { return Mouse () } = "Mouse"}
I then defined two classes that implement the animal protocol, where the printable protocol is purely for printing convenience;
At the same time, I defined a paradigm method to invoke the Newinstance method:
Func printanimal<t:animal>(type:t.type) { println (Type.newinstance ())}
Execute the following statement:
Printanimal (dragon.self) printanimal (mouse.self)
The result is:
Dragon
Mouse
Types of Swift language methods