Swift's as, as!, as?

Source: Internet
Author: User

1,as Use occasions
(1) converting from derived class to base class, upward transformation (upcasts)

1 class Animal {} 2 class Cat:animal {} 3 Let cat = cat ()4 as Animal

(2) Elimination of ambiguity, numeric type conversion
1  the  as CGFloat 2  the  as Int 3 42.5  as Int 4 Let num4 = (2 as Double

(3) pattern matching in a switch statement
If you do not know what type an object is, you can detect its type through the switch syntax, and try to use the corresponding type for the appropriate processing in different situations.

1 SwitchAnimal {2  CaseLet Cat asCat:3Print"if it is a cat type object, do the appropriate processing")4  CaseLet dog asDog:5Print"if it is a dog type object, do the appropriate processing")6 default: Break7}

2,as! Use occasions

used when transforming downward (downcasting). Because it is a forced type conversion, a runtime run error is reported if the conversion fails.

1 class Animal {} 2 class Cat:animal {} 3 let animal:animal  = Cat ()4as! Cat

3,as? Use occasions

As? and as! The conversion rules for the operators are exactly the same. But as? If the conversion is unsuccessful, a nil object is returned. If successful, return the optional type value (optional), we need to split the package to use.
Because of as? There is no error when the conversion fails, so you can use as! if you can make sure that 100% is successful, otherwise use as?

1 Let animal:animal = Cat ()23ifas? cat{4     print ("Cat is not nil")5  else  {6     print ("cat is nil")7  }

Note: Derived classes:

Ambiguity
The question of ambiguity
1. When inheriting, when a member has the same name between a base class, or between a base class and a derived class, there is uncertainty about member access--two semantics with the same name.
2. When derived classes derive from more than one base class and derive from the same base class, another uncertainty-the path ambiguity-is generated when accessing members in this common base class.

Swift's as, as!, as?

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.