Swift::3:: Optional value

Source: Internet
Author: User

Selectable VALUES (Optional)

In OC, a class-type variable whose value can be either a valid object or nil. However, types such as int,double do not have nil values. For example, 32-bit int, which exceeds the maximum, OC is treated with nsnotfound instead of the nil value. Swift is more flexible than OC and supports all types of canon with nil values-selectable values (Optional)-directly at the syntactic level

How to use

With optional values, Swift provides a very concise way to add '? ' directly to the type. ', for example, to define an integer variable with an optional value:

var optionalinteger:int?

After you run Xcode playground, you can see the following effects:

Unpack (unwrapped)

Swift is a strongly typed language, so when the above optionalinteger is used, Swift does not want it to be an optional value, it must be an int, so it needs to be unpacked--simply understood, or transformed. Unpacking the operation, is also very simple, after the variable add '! ', such as:

var Normalinteger = optionalinteger! + 5

Value binding (binding)

The premise of unpacking is that you are sure that the variable is not nil, otherwise the forced unpacking is unsafe, Swfit provides another very concise syntax to check whether the pre-unpacking ratio is nil value-that is, value binding, again using Optionalinteger as an example:

If let Tempinteger = optionalinteger{    Normalinteger = tempinteger + 5     }else {    //nil, do something}

Note that after the Tempinter is assigned, its value is not optional, but int, so no unpacking is required.

This article, refer to http://www.codingexplorer.com/swift-optionals-declaration-unwrapping-and-binding/

Swift::3:: Optional value

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.