Optional variables in Swift

Source: Internet
Author: User

Today we understand the optional variables in swift, namely:

var a? A is an optional value here, meaning that the value may be missing.

There is a value, equal to X, or no value.

See this example, the optional type section from http://www.swiftmi.com/swiftbook_cn/chapter2/01_The_Basics.html

Swift's string type has a method called ToInt that converts a string value into an int value. However, not all strings can be converted to an integer. The string "123" can be converted to the number 123, but the string "Hello, World" does not work.

The following example uses the ToInt method to try to convert a string into an int:

  

Because the ToInt method may fail, it returns an optional (optional) int instead of an int. An optional int is written int? instead of Int. The question mark implies that the value contained is optional, that is, may contain an int value or may not contain a value. (cannot contain any other value, such as a bool value or a string value.) It can only be int or nothing. )

If statements and forced parsing

You can use the IF statement to determine whether an optional value is included. If there is an optional value, the result is true, and if there is no value, the result is false.

After you have determined that the optional package does contain a value, you can add an exclamation mark (!) to the optional name. To get the value. This exclamation point says "I know this option has a value, please use it." "This is called forced parsing of optional values (forced unwrapping):

1 ifConvertednumber {2println"\ (possiblenumber) has an integer value of \ (convertednumber!)") 3}Else { 4println"\ (possiblenumber) could not being converted to an integer") 5 } 6 //output "123 have an integer value of 123"

NOTE: Use! To obtain an optional value that does not exist causes a run-time error. Use! To force a value to be parsed, be sure to include a non-nil value.

Optional variables 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.