[Swift] Day12: type conversion, swiftday12

Source: Internet
Author: User

[Swift] Day12: type conversion, swiftday12
Type Conversion Type Determination

We can useisTo determine whether an instance belongs to a specified class or its subclass. The function is similarOCInisKindOfClass.

Here is a simple example:

class A {}class B: A {}class C: A {}var array = [B(),A(),C(),A()]   // [A]for item in array {    if item is B {        println("B")    // 1 time    }    if item is C {        println("C")    // 1 time    }    if item is A {      // ERROR! ALWAYS TRUE        println("C")    // 1 time    }}
Downward Transformation

You can use the type conversion operator.asTry to convert an instance to its subtype. The conversion does not actually change the instance or its value. The underlying potential Instance remains unchanged, but simply uses it as the class it is converted.

For example, the following code:

class A {}class B: A {}class C: A {}var array = [B(),A(),C(),A()]   // [A]for item in array {    if let aB = item as? B {        println("aB")    // 1 time    }    if let aC = item as? C {        println("aC")    // 1 time    }}
Any And AnyObject

Swift provides two special types of aliases for uncertain types:

  • Any can represent Any type, except function types ).
  • AnyObject can represent any class type instance.
References
  • TypeCasting

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.