Generics

Generics are another important object-oriented concepts in,In addition to multi-state,It further increases the range of reuse code,For Swift language,,Generics throughout its always。

From Print() Speaking

We start from the first day of class in the use of this global function,It allows us to show the statement on the screen,Very simple to use,It can pass a string。

Incoming string displayed string,Incoming shaping on the digital display ......

and many more! As a function,How can it receives two different parameters!

Well, we use everything cmd button,Look at this point into print() Exactly how the function declaration:

If there are no generics

From now on,Let's write a method to exchange two numbers (copied from Apple's official manual)

If you want to use,It is used:

Now I want to swap two strings:

I would also like to swap two double-precision floating-point number:

That is,Now we owned the Int,String ,Double version of the exchange location method - their only difference is a different type。This is not consistent with the principles of our development - the same content is repeated too many - thousands and thousands of types,Not including our own type definition,Are so exchange,that……

Using generics rescue field

Such,Whether Int or String,Or even write your own types,You can step in place。

 

Generics

We use T to represent a placeholder - Plainly it is a wildcard,We do not restrict incoming parameter of type,The only requirement is that the type of these two parameters have to be consistent。Then we use the method of angle brackets behind<>Enclose a placeholder,On behalf of this method is a generic method。

the following,We come to realize a structure with generics:

This is a plastic stack - the concept we have talked about the stack,An object oriented execution of which is to be completed in the stack,Now we write a plastic stack,This includes two methods of the stack and the stack - apparently,This structure can also be transformed into other types of stacks ...... now we need it to be implemented generics:

You see,This time we use the Element as a placeholder,The key is to use<>It can display。

Such,We just need to show the type when generating instances,This structure can be used corresponding to the type of。

Original article written by LogStudio:R0uter's Blog » Generics

Reproduced Please keep the source and description link:https://www.logcg.com/archives/1138.html

About the Author

R0uter

The non-declaration,I have written articles are original,Reproduced, please indicate the link on this page and my name。

Leave a Reply

Your email address will not be published. Required fields are marked *