Optional types in Swift

Source: Internet
Author: User
Tags unpack

A few days ago turned an introduction, and exclamation of the article, now I understand, record!

The optional type variable in 1.swift indicates that the variable might have a value or be empty. You might think this is going to be done with just one pointer? However, Swift does not support pointers. (This explanation is somewhat farfetched, but a syntax error occurs when assigning a value of nil to an ordinary variable).

2. Both question marks and exclamation mark can declare optional type variables in swift, such as:

var num:int? = 10

var num1:int! = 11

3. There is a difference between the two ways of declaring the top

A variable that is declared by a question mark must force the unpacking assignment to a variable of a specific type when used

The variable of the exclamation mark Declaration does not need to be forced to unpack when it is in use this step the compiler has done for us.

4. A variable that declares to be an optional type is forced to unpack (forcing the unpacking to add an exclamation mark behind an optional variable) must be judged, because a variable of an optional type can cause a program to crash if it has no value.

5. The variable of the optional type is stored in a different way than the normal variable is stored by default there is a value of none (that is, nil value) and then there is a some to store the real data

6. Personal use of the impression: when the initialization is not sure whether this property has a value when the optional type can be used, as for the choice of forced unpacking, or implicit unpacking this according to personal habits!

Optional types in Swift

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.