What is the use of the optional type (Optional) in Swift? And! The difference (reprint blog, knowledge sharing)

Source: Internet
Author: User

 

This article reproduced from: Code Craftsman's Blog, original name: Swift? And!

The swift language uses VAR to define variables, but unlike other languages, Swift does not automatically assign an initial value to a variable, which means that the variable does not have a default value, so it must be initialized before it is required to use the variable. If you do not initialize before using the variable, you will get an error:

C code
    1. var stringvalue:string
    2. Error:variable ' stringvalue ' used before being initialized
    3. Let HashValue = Stringvalue.hashvalue
    4. //                            ^
    5. Let HashValue = Stringvalue.hashvalue

The above is the normal value, the next optional value to play. Through the meow God reminds, Optional is actually a enum , inside have None and Some two kinds of. In fact, the so-called nil is, Optional.None non-nil is Optional.Some , and then through the Some(T) wrapping (Wrap) The original value, which is why in the use of optional when the package (from the enum to take out the original value) reason, Also playground will show the optional value as a similar {Some "hello world"} reason, here is the definition of enum optional:

C code
  1. Enum optional<t>: Logicvalue, reflectable {
  2. Case None
  3. Case Some (T)
  4. Init ()
  5. Init (_ Some:t)
  6. //allow use with in a Boolean context.
  7. Func getlogicvalue (), Bool
  8. // Haskell ' s Fmap, which was mis-named
  9. Func map<u> (f: (T)-U)-u?
  10. Func getmirror ()-Mirror
  11. }

Declaring as optional only needs to be followed by a type ? . Such as:

C code
    1. var strvalue:string? //? The syntax sugar equivalent to the following notation
    2. var strvalue:optional<int>

Once declared as optional, there is a default value of nil if no explicit assignment is made. To determine whether a optional value has a value, you can use the IF to determine:

C code
    1. If strvalue {
    2. //do sth with strvalue
    3. }

And then how to use the optional value? It is also mentioned in the documentation that the use of Optional values requires a specific operation, such as calling methods, attributes, subscript indexes, and so on before adding a ? , by Meow, "Optional chaining question mark means to ask whether to respond to the following method, and the original isResponseToSelectorsome of the similar ", if it is nil value, that is Optional.None , is not able to respond to the following method, so it will be skipped, if there is a value, that is Optional.Some , it is possible to split the package (unwrap), and then the value after the split to perform subsequent operations, such as:

C code
    1. Let HashValue = strvalue?. HashValue

Strvalue is a string of optional, if strvalue is nil, then HashValue is nil, if strvalue is not nil,hashvalue is the hash value of the strvalue string

Here ? are two usage scenarios we've seen:
1. Declaring a optional value variable
2. Used in the optional value operation, to determine whether to respond to the subsequent operation

In addition, for the optional value, can not directly operate, otherwise will be error:

C code
    1. Error: ' String? ' does not has a member named ' HashValue '
    2. Let HashValue = Strvalue.hashvalue
    3. //                ^        ~~~~~~~~~
    4. Let HashValue = Strvalue.hashvalue

The above mentioned optional value needs to be split (unwrap) to get the original value before it can be manipulated, then how to split the package? Unpacking refers to several methods, one of Optional Binding which is, for example:

C code
    1. If let str = strvalue {
    2. Let HashValue = Str.hashvalue
    3. }

There is also a specific operation before the addition of ! symbols, OK, this is what weird grammar?!

Directly on the example, strvalue is the optional string:

C code
    1. Let HashValue = strvalue!. HashValue

Here's the ! expression "I'm sure the strvalue here must be non-nil, call it", like this:

C code
    1. If strvalue {
    2. Let HashValue = strvalue!. HashValue
    3. }

{} The strvalue must be non-nil, so you can add it directly!, Force unpacking (unwrap) and perform the subsequent operations. Of course, if you do not add judgment, strvalue is not careful for nil, it will be wrong, crash off.

Consider this scenario, we have a custom MyViewController class with a property in the class that myLabel MyLabel is initialized in Viewdidload. Because it is initialized in Viewdidload, it cannot be declared directly as a normal value: var myLabel : UILabel because a non-optional variable must be initialized at the time of declaration or in the constructor, but we want to initialize it in Viewdidload, we can only declare it as optional: var myLabel: UILabel?, although we determine that it will initialize in Viewdidload and will not be set to nil for the lifetime of the Viewcontroller, but in the case of mylabel operations, it is always added ! to force the unpacking (when reading the value, you can also use the ?, thank you for ipresent in the reply), such as:

C code
    1. mylabel!. Text = "text"
    2. mylabel!. frame = CGRectMake (0, 0, 10, 10)
    3. ...

For this type of value, we can directly declare: var myLabel: UILabel! , is really high (Hao) large (GUI) on the syntax!, this is a special optional, called Implicitly Unwrapped Optionals , literal translation is the optional of the implicit unpacking, it is equal to say every time you operate on this type of value, will automatically fill in before the operation of the ! unpacking, and then perform the subsequent operations, of course, if the value is nil, also will be the same error crash off.

C code
    1. var mylabel:uilabel! //! equivalent to the syntax of the following notation sugar
    2. var mylabel:implicitlyunwrappedoptional<uilabel>

Then ! there are probably two use cases
1. Forcing the optional value to be split (unwrap)
2. Declaring Implicitly Unwrapped Optionals values, typically used for properties in a class

Swift is the language of the new door, we have the honor to witness the birth of it, but also in admiration of the excitement of Apple's bold launch of a new language to replace a more mature language, today in the daily read the answer is that Swift is a toy language, just want to spit groove, found that the answer has been deleted. Personally, Apple is very serious about the introduction of swift, from Swift's various subtle designs can also be seen.

In addition, these two small symbols took me a lot of time to understand, there may still be errors and irregularities, welcome to correct, this article is intended to introduce. In addition, Swift has a lot of great features, WWDC 2014 will have four or five and swift language-related video, you can also pay attention to.

Finally to thank the Meow God corrected a number of problematic places, thx, have fun!

The main reference is from Apple's official document "The Swift programming Language", which can be downloaded here

What is the use of the optional type (Optional) in Swift? And! The difference (reprint blog, knowledge sharing)

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.