Swift development of AS, as!, as? Three types of conversion operators use the detailed

Source: Internet
Author: User

At the request of netizens, I have summed up the following as, as!, as? The similarities and differences of these three types of conversion operators, as well as their respective usage scenarios.

1,as Use Occasion

(1) Convert from derived class to base class, transition upward (upcasts)

Class Animal {}
Class Cat:animal {}
Let cat = Cat ()
Let animal = cat as Animal

(2) Elimination of ambiguity, numeric type conversion


Let NUM1 = CGFloat
Let num2 = ' as Int '
Let num3 = 42.5 as Int
Let num4 = (42/2) as Double

(3) Pattern matching in switch statements

If you do not know what type of object is, you can detect its type by switch syntax and try to handle it in different situations using the corresponding type.


Switch Animal {
Case let Cat as Cat:
Print ("If it is a cat type object, do it appropriately")
Case let dog as dog:
Print ("If it is a dog type object, do the appropriate processing")
Default:break
}

2,as! Use Occasion

The downward Transition (downcasting) is used. Because it is mandatory type conversion, a runtime run error is reported if the conversion fails.


Class Animal {}
Class Cat:animal {}
Let Animal:animal = Cat ()
Let cat = Animal as! Cat

3,as? Use occasion

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


Let Animal:animal = Cat ()

If let cat = animal as? cat{
Print ("Cat is not nil")
} else {
Print ("Cat is nil")
}

Original: www.hangge.com

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.