[Swift] DAY12: Type Conversion

Source: Internet
Author: User

Type conversion type judgment

We can is determine whether an instance belongs to a specified class or its subclasses, and functions like this OC isKindOfClass .

Let's demonstrate by a simple example:

Class A {}class b:a {}class c:a {}varArray = [B (), A (), C (), A ()]//[A] forIteminchArray {ifItem isB {println ("B")//1 time}ifItem isC {println ("C")//1 time}ifItem isA//error! Always TRUEprintln"C")//1 time}}
Down transformation

You can use the type conversion operator to as try to convert an instance to its subtype. The conversion does not really change the instance or its value. The underlying root instance remains the same, simply using it as the class it is converted to.

For example, the following code:

classA {}classb:a {}classc:a {}varArray = [B (), A (), C (), A ()]//[A] forIteminchArray {if  LetAB = Item as? B {println ("AB")//1 time}if  LetAC = Item as? C {println ("AC")//1 time}}
Any and Anyobject

Swift provides two special types of aliases for indeterminate types:

    • Any can represent any type except the method type (function types).
    • Anyobject can represent instances of any class type.
References
    • Typecasting

[Swift] DAY12: Type Conversion

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.