Swift Learning notes-optional?

Source: Internet
Author: User

Optional type

Use an optional type (optionals) to handle situations where the value may be missing. The optional type represents:

    • has a value equal to X

Or

    • No value

Attention:
There is no concept of optional type in C and objective-c. The closest is a feature in Objective-c, a method that either returns an object or returns a nil nil "missing legitimate object". However, this only works on objects--for structs, the basic C type or enumeration type does not work. For these types, the Objective-c method typically returns a special value (for example NSNotFound ) to imply that the value is missing. This approach assumes that the caller of the method knows and remembers to judge the particular value. However, the optional type of Swift allows you to imply that any type of value is missing and does not require a special value.

Take a look at an example. The String type of Swift has a toInt method called, which is to String convert a value into a Int value. However, not all strings can be converted to an integer. Strings "123" can be converted to numbers 123 , but "hello, world" not strings.

The following example uses the toInt method to try to String convert one into Int :

let possibleNumber = "123"let convertedNumber = possibleNumber.toInt()// convertedNumber 被推测为类型 "Int?", 或者类型 "optional Int"

Because toInt the method may fail, it returns an optional type (optional)instead of Int one Int . An optional Int is written instead of Int? Int . The question mark implies that the value contained is an optional type, meaning that it may or may not contain a value Int . (cannot contain any other value, such as a Bool value or a value String .) There's only one thing Int or nothing. )

If statements and forced parsing

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

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

if convertedNumber {    println("\(possibleNumber) has an integer value of \(convertedNumber!)")} else {    println("\(possibleNumber) could not be converted to an integer")}// 输出 "123 has an integer value of 123"

For more information about if statements, refer to control flow.

Attention:
Use ! to get an optional value that does not exist causes a run-time error. !before you use to force parsing a value, be sure to include an optional value that is not nil .

Optional bindings

The optional binding (optional binding) is used to determine whether an optional type contains a value, and if it is included, assigns the value to a temporary constant or variable. Optional bindings can be used in if and while statements to determine the value of an optional type and assign a value to a constant or variable. ifand while statements, refer to control flow.

ifWrite an optional binding in the statement like this:

if let constantName = someOptional {    statements}

You can override this example with an optional binding like this possibleNumber :

if let actualNumber = possibleNumber.toInt() {    println("\(possibleNumber) has an integer value of \(actualNumber)")} else {    println("\(possibleNumber) could not be converted to an integer")}// 输出 "123 has an integer value of 123"

This code can be understood as:

"If the possibleNumber.toInt returned optional Int contains a value, create a actualNumber new constant called and assign the optional included value to it." ”

If the conversion succeeds, a actualNumber constant can be used in the if first branch of the statement. It has been initialized with the value contained by the optional type, so you do not need to use ! the suffix to get its value. In this example, it actualNumber is only used to output the conversion results.

You can use constants and variables in optional bindings. If you want to if manipulate the value in the first branch of the statement actualNumber , you can change it if var actualNumber so that the optional type contains a value that will be assigned to a variable and very much.

Nil

You can assign a value to an optional variable to nil indicate that it has no value:

var serverResponseCode: Int? = 404// serverResponseCode 包含一个可选的 Int 值 404serverResponseCode = nil// serverResponseCode 现在不包含值

Attention:
nilcannot be used for non-optional constants and variables. If you have constants or variables in your code that need to deal with missing values, declare them as the appropriate optional type.

If you declare an optional constant or variable but do not assign a value, they are automatically set to nil :

var surveyAnswer: String?// surveyAnswer 被自动设置为 nil

Attention:
Swift is nil not the same as in Objective-c nil . In Objective-c, nil is a pointer to a nonexistent object. In Swift, nil it is not a pointer-it is a definite value that is used to denote a missing value. any type of optional state can be set to nil , not just the object type.

implicitly resolves an optional type

As mentioned above, an optional type implies that a constant or variable can "have no value". Optionally, the statement can be used to if determine if there is a value, and if so, the value can be resolved by an optional binding.

Sometimes in the program architecture, after the first assignment, you can determine that an optional type always has a value. In this case, it is very inefficient to judge and parse an optional value every time, because you can be sure that it always has a value.

An optional state of this type is defined as an implicitly resolved optional type (implicitly unwrapped optionals). String?declare an implicitly resolved optional type by changing the following question mark () to an exclamation point () that you want to use as an optional type String! .

Implicit parsing of optional types is useful when an optional type is assigned the first time after it can be determined that there is always a value. Implicit parsing of optional types is primarily used in the construction of classes in Swift, refer to cyclic strong references between class instances.

An implicit parsing optional type is actually a normal optional type, but can be used as a non-optional type and does not require parsing to get an optional value each time. The following example shows the difference between an optional type String and an implicitly resolved optional type String :

let possibleString: String? = "An optional string."println(possibleString!) // 需要惊叹号来获取值// 输出 "An optional string."
let assumedString: String! = "An implicitly unwrapped optional string."println(assumedString)  // 不需要感叹号// 输出 "An implicitly unwrapped optional string."

You can consider an implicit parsing optional type as an optional type that can be parsed automatically. All you have to do is declare the exclamation point at the end of the type, not at the end of the optional name each time the value is taken.

Attention:
If you try to take a value when you implicitly parse an optional type without a value, a run-time error is triggered. And you add an exclamation mark after a normal optional type that has no value.

You can still determine whether an implicit parsing optional type is a normal optional type to see if it contains a value:

if assumedString {    println(assumedString)}// 输出 "An implicitly unwrapped optional string."

You can also check and resolve the value of an optional binding by using an implicitly resolved optional type:

if let definiteString = assumedString {    println(definiteString)}// 输出 "An implicitly unwrapped optional string."

Attention:
nildo not use implicit parsing of optional types If a variable is likely to change after that. Use the normal optional type if you need to determine whether it is in the lifetime of the variable nil .

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.