Swift's? And!

Source: Internet
Author: User

Original: Http://joeyio.com/ios/2014/06/04/swift---/

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:

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. Optional is actually a enum , there are None and Some two kinds of types. 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:

EnumOptional<T>:Logicvalue,Reflectable{CaseNoneCaseSome(T)Init()Init(_some: t ///allow with in a Boolean Context. func getlogicvalue () -> Bool Span class= "C1" >///Haskell ' s Fmap, which was mis-named func map<< span class= "n" >u> (f:  t) -> u) -> ufunc getmirror () -> Mirror< Span class= "P" >               

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

var strValue: String? //?相当于下面这种写法的语法糖var strValue: Optional<String>

The above statement of optional, meaning "I declare a string value of optional", but "I declare a optional type value, which may contain a string value, or it may contain nothing", That is to say, we are actually declaring the optional type, rather than declaring a string type, which we need to keep in mind.

It is advisable to read the previous paragraph again.

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:

if strValue {    //do sth with strValue}

And then how to use the optional value? It is also mentioned in the document that the use of the optional value is required in the specific operation, such as calling methods, properties, subscript index, and so on before the need to add a ? , if it is nil value, that is Optional.None , will skip the subsequent operation is not executed, if there is a value, that is Optional.Some , may be unpacking (unwrap), then perform the subsequent operation on the value after unpacking to ensure the security of this operation, such as:

let hashValue = strValue?.hashValue

Strvalue is a optional string, if strvalue is nil, then HashValue is nil, if strvalue is not nil,hashvalue is the hash of the strvalue string (in fact optional The value after wrap)

Also, it can be used to safely invoke the protocol type method, such as:

@ObjCProtocolDownloadable{@optionalfunc download (topath: string) -> bool;} @objc class content: downloadable {//download method not being Implemented }var delegate: downloadable = span class= "n" >downloadable () delegate. Download? ( "some path" )            

Because the above delegate is the downloadable type, its download method is optional, so it's concrete implementation has download no method is indeterminate. Swift provides a ? way to safely call protocol's optional method before the parameter brackets are added.

In addition, if you need to change downward like this (downcast), you may use as? :

if let dataSource = object as? UITableViewDataSource { let rowsInFirstSection = dataSource.tableView(tableView, numberOfRowsInSection: 0)}

Here ? are a few of the 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
3. Optional method for secure call to protocol
4. Using as? Down Transformation (downcast)

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

//error: ‘String?‘ does not have 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:

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:

let hashValue = strValue!.hashValue

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

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 ?), such as:

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.

var myLabel: UILabel! //!相当于下面这种写法的语法糖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's? 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.