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
- var stringvalue:string
- Error:variable ' stringvalue ' used before being initialized
- Let HashValue = Stringvalue.hashvalue
- // ^
- 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
- Enum optional<t>: Logicvalue, reflectable {
- Case None
- Case Some (T)
- Init ()
- Init (_ Some:t)
- //allow use with in a Boolean context.
- Func getlogicvalue (), Bool
- // Haskell ' s Fmap, which was mis-named
- Func map<u> (f: (T)-U)-u?
- Func getmirror ()-Mirror
- }
Declaring as optional only needs to be followed by a type ?
. Such as:
C code
- var strvalue:string? //? The syntax sugar equivalent to the following notation
- 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
- If strvalue {
- //do sth with strvalue
- }
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 isResponseToSelector
some 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
- 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
- Error: ' String? ' does not has a member named ' HashValue '
- Let HashValue = Strvalue.hashvalue
- // ^ ~~~~~~~~~
- 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
- If let str = strvalue {
- Let HashValue = Str.hashvalue
- }
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
- Let HashValue = strvalue!. HashValue
Here's the !
expression "I'm sure the strvalue here must be non-nil, call it", like this:
C code
- If strvalue {
- Let HashValue = strvalue!. HashValue
- }
{} 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
- mylabel!. Text = "text"
- mylabel!. frame = CGRectMake (0, 0, 10, 10)
- ...
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
- var mylabel:uilabel! //! equivalent to the syntax of the following notation sugar
- 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)