Swift summary using question mark (?) and exclamation point (!)-Alternate

Source: Internet
Author: User

When using optional types and optional chains, the question mark (?) and exclamation point (!) are used more than once,but they have different meanings, let me explain in detail below.  

1. Question mark (?) in the optional type

Declares that this type is an optional type, to use an exclamation point (!) when accessing a variable or constant of this type, and the following code shows the split package:

 
    1. Let result1:double? = Divide (100, 200)
    2. Print (result1!)


 

2. Exclamation mark (!) in an optional type

Declaring this type is optional, but you can access this type of variable or constant without using an exclamation point (!), and the following code is implicitly unpacking:

 
    1. Let result3:double! = Divide (100, 200)
    2. Print (RESULT3)


 

3. Exclamation point in the optional chain (!)

Multiple instances have an association, and a reference chain is formed when a member of another instance's methods, properties, and subscripts are referenced from one instance, and since some links in this "chain" may have values or no values, they need to be accessed in the following way:

 
    1. Emp.dept!.comp!.name


4. Question mark (?) in the optional chain

When using an exclamation mark (!) in an optional chain,once the "chain" has no value, the program will have an exception, we'll change the exclamation point (!) to a question mark (?), and the code looks like this:

 
    1. Emp.dept?.comp?.name


This returns nil when there are no values for certain links , and the program does not have an exception.

Swift summary using question mark (?) and exclamation point (!)-Alternate

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.