Swift Learning-swift? And!

Source: Internet
Author: User

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.hashva lue//                            ^let hashValue = Stringvalue.hashvalue
the above is the normal value, the next optional value to play. byMeow Godremind that optional is actually aEnum, there areNoneand theSometwo different types. In fact, the so-called nil isOptional.none, non-nil isOptional.some, and then you passSome (T)Wrapping (Wrap) raw value, which is why the optional is used to unpack (the original value from the enum), and playground will show the optional value as similar{Some "Hello World"}The reason for this is the definition of enum optional:

Enum optional<t>: Logicvalue, reflectable {case-    None case    Some (T)    init ()    init (_ Some:t)    // /Allow 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}
declared as optional only need to be behind type Follow a?can be. such as:

var strvalue:string?   ? The syntactic sugar var strvalue:optional<string> equivalent to the following notation

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 documentation that the use of the optional value requires a specific operation, such as calling methods, attributes, subscript indexes, etc. before adding a?, if it is a nil value, which isOptional.none, the subsequent operation is skipped, and if there is a value, it isOptional.some, it is possible to remove the package (unwrap) and then perform subsequent operations 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:

@objc protocol Downloadable {    @optional func download (topath:string), Bool;} @objc class Content:downloadable {    //download method not being Implemented}var delegate:downloadable = downloadable () de Legate.download? ("Some path")

because the above delegate is of type downloadable, its download method is optional, so it's concrete implementation there is no download method is indeterminate. Swift provides a way to safely call protocol's optional method by adding one to the parameter brackets.

Also if you need to move down like this (downcast), you might use as?:

If let DataSource = object as? Uitableviewdatasource {Let    rowsinfirstsection  = Datasource.tableview (TableView, numberofrowsinsection:0)}

we've seen it here. ? Several usage scenarios:

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 has a member named ' HashValue '//let hashValue = strvalue.hashvalue//                ^        ~~~~~~~~~let h Ashvalue = 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 is Optional Binding, such as:

If let str = strvalue {let    hashValue = Str.hashvalue}

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

Directly on the example, strvalue is the optional string:

Let HashValue = strvalue!. HashValue

Here's ! "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 case, 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. So it can only be declared 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, Always add! To force unpacking (when reading the value, also can use?, thank you ipresent in reply), such as:

mylabel!. Text = "Text" mylabel!. frame = CGRectMake (0, 0, 10, 10) ...

for this type of value, we can declare this directly:var mylabel:uilabel!, sure enough, is high (Hao) large (GUI) on the syntax!, this is a special optional, calledimplicitly unwrapped optionals, literal translation is the optional of the implicit unpacking, which means that each time you operate on this type of value, it automatically adds a!to do the unpacking, and then perform the subsequent operation, of course, if the value is nil, the same error will be crash off.

var mylabel:uilabel!  This is equivalent to the syntax of the following notation sugar var mylabel:implicitlyunwrappedoptional<uilabel>

so ! There are probably two usage scenarios

1. Forcing the optional value to be split (unwrap)
2. DisclaimerImplicitly unwrapped Optionalsvalues, 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!

Swift Learning-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.