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