How to understand optional in Swift! And?

Source: Internet
Author: User

Tag: The code default value that does not complete the something value of the Times reminds it

Many people do not understand the use of optional '! ' and '? ' in the beginning of Swift, and then I talk about my understanding of how these two symbols are used.

First of all, say the concept of optional, to facilitate the understanding later. Take a look at the following code:

var a:string = nil//Compile error, String type cannot be nil
var b:string = "Hello!"
1
2
The normal type in Swift can no longer be set to nil. How does that mean that the value does not exist? So the concept of optional is introduced: it represents nil or a specific value. For example:

var c:string? = Nil
var d:string? = "Hello!"
1
2
String? is a optional that can be assigned to either a specific type or nil. By comparing String and optional, it is found that optional is the equivalent of bundling a specific type with nil packaging and turning it into a new type.

There are two methods of declaring Optional:

var apple:string?
var bread:string!
1
2
Many people think that the declaration as string! Variable indicates that the value of the variable is not nil. But, in fact, string! and String? Have default values, and the default value is nil. We'll give them an initial value. Reprint type look at:

var apple:string? = "Apple"
var bread:string! = "Bread"
1
2
(LLDB) P Apple
(String?) $R 0 = "Apple"

(LLDB) P bread
(String?) $R 1 = "bread"

Found that even though Apple and bread are a String? One is string!. But the print is a String? Type of. So the more appropriate understanding should be: string! Just understand the meaning of the non-nil, its essence is a Optional, from the statement that it and String? is completely equivalent, so it can also be assigned to nil.

For later narrative convenience, we put the definition like a String? Called Optional (www.chonylpt.com?), which defines a similar string! is called Optional (!).

The essence of Optional is an enumeration that includes nil and specific types. The procedure for obtaining its specific value is called unpacking, denoted by "!". Let's do an experiment first:

var string:string
var optionalstring:string?
var nonoptionalstring:string!

String = nonoptionalstring//① crashes
string = optionalstring//② compile wrong
string = optionalstring! ③ crashes
Specific look at the cause of the error:
①string! Assign to String, error: When unpacking, the value of optional is nil;
②string? Assign to String, compiler error is optional not unpacking;
③ the String after unpacking the package? Assigned to String, at this time, the error is: When unpacking the value of optional is nil;
string! And the String after unpacking? The error of the pass times is the same, so we can draw a conclusion: the compiler default Optional (!) is determined to have a value, so there is no need to deal with nil. The Optional (!) variable simply gives the automatic unpacking permission and does not need to use '! ' for unpacking in the actual process of using it. In the official Swift document, it is known as: Implicitly unwrapped Optional (implicit unpacking), also can be understood as "split the package."

However, the package can only be disassembled if the variable is confirmed to have a value. Just like the code above, optionalstring is nil and unpacking will cause a crash. Swift official recommends that Optional use if +! A combination of means or if let to safely disassemble the package. Simply look at the code:

If optionalstring! = Nil {
Append (string:www.078881.cn/optionalstring!)
} else {
Do something

If let actualstring = optionalstring {
Append (string:actualstring)
} else {
Do something
Again, Optional (!) and www.yongshiyule178.com Optional (?) can be safely split in both ways, except that the compiler will not error the Optional (!) that did not handle nil.

Shows a comparison of Optional and String-acceptable types:

The Optional after unpacking is actually a String type. The compiler forces the user to process when the variable is nil, or the error will crash. string! is to avoid the variable must not be nil in the case of repeated judgment whether it is nil redundant code generated. For example, when we use iboutlet, we are bound to define OPTIONA (!). string! At the time of declaration and String? Exactly equivalent, when used and String is exactly equivalent.

To summarize:

The essence of optional is an enumeration that contains nil and a generic type, which is to ensure that the user will complete the corresponding processing in the case where the variable is nil;
Whether Optional (!) or Optional (?) is a Optional, the default is nil when no initial value is set. Optional (!) simply gives the automatic unpacking permission, omitting the process of judging whether its value is nil, but cannot guarantee that its value is not nil;
Optional (!) is equivalent to Optional (?) at the time of Declaration and is equivalent to the specific type when used;
It is important to ensure that the Optional is not nil and can be split directly, or it will cause a crash.

How to understand optional in Swift! And?

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.