Types of Swift language methods

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.