Swift Optional Type-standby

Source: Internet
Author: User

Let's start by looking at the following code:

 
    1. var N1: Int = Ten
    2. N1 = Nil//Compile error
    3. Let str: String = Nil//Compile error

int and string types cannot accept nil, but sometimes it is unavoidable that the program is copied to nil during the run , andSwift provides an optional type (optional) for each data type. That is, after a data type with a question mark (?) or exclamation point (!), modify the preceding example code:

 
    1. var n1:int? = 10
    2. N1 = Nil
    3. Let str:string! = Nil

int? and string! are both original type int and String optional types, they can accept nil.

Optional type value unpacking

What is the difference between a question mark (?) or an exclamation point (!) in an optional type? This is related to the "unpacking" (unwrapping) of the optional type, which is to turn the optionaltype into a normal type, and if we print a non-empty optional type value directly, the code is as follows:

 
    1. var n1:int? = 10
    2. Print (N1)

The result of the output is Optional (10), not 10. So trying to evaluate the expression n1+ 100 will compile error, the code is as follows:

 
    1. var n1:int? = 10
    2. Print (n1 + 100)//Compile error occurred

It is necessary to "disassemble" the optional type value.

"Unpacking" is divided into show unpacking and hidden unpacking.

an optional type declared with a question mark (?) that requires an exclamation point (!) when unpacking,which is called an explicit unpacking;

Anoptional type declared with an exclamation point (!) that can be split without using an exclamation point (!), which is called an implicit unpacking.

Take a look at the following code:

 
      1. var n1:int? = 10
      2. Print (n1! + 100)//Explicit unpacking
      3. var n2:int! = 100
      4. Print (n2 + 200)//implicit unpacking

Swift Optional Type-standby

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.