iOS Swift! and?

Source: Internet
Author: User

Swift? And! Difference between:

Perhaps the most unusual thing that Swift has introduced is Optional Value. At the time of declaration, we can declare a variable to be Optional by adding one after the type ? . If it is not a Optional variable, then it must have a value. And if there is no value, we use Optional and set it to nil indicate no value.

// num is not an Intvar num:int?  // num has no value num = nil  //  nil//num has a value of 3      {Some 3}  

Apple tells us at the session that Optinal value is actually a box, you may have actual values in the box, and you may not have anything to wear.

We see in the Session or in the document every day said Optional Optional, but we in the code of basic a Optional do not see, this is why? And why does the output of the above code num look a bit odd when assigned a value of 3? In fact, when declaring a type, this is ? just a syntactic sugar that Apple provides in order to simplify the wording. In fact, we have a Optional type of statement, num for example here, the most formal wording should be this:

// true Optional declaration and use var num:optional<int>  = optional<int>()  = Optional <Int> (3)  

Yes, num is not Int type, it is a Optional type. What exactly is it Optional , point in to see:

 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)?  Func Getmirror () -> Mirror}  

you might be surprised. The Optional that we deal with with Swift every day is actually a generic enumeration   enum , and when we use this enumeration, if there is no value, we specify that the enumeration is   . None , if any, then it is Some (value) (with value enumeration do not expand here, if you do not understand, please read the document). And this enumeration happens to implement the logicvalue   interface, which is why we can use   if   To judge the value of a optinal and further unwrap the basis.

3  if num {       // because there is Logicvalue                 ,//. None when Getlogicvalue () returns false               //. Some returns True when   var realint = num!    Realint     //3}

since var num: Int? = nil actually give num The value of the assignment is an enumeration, then this nil What the hell is that? Where has it been assigned to? It has been noted that nil in Swift and nil in OBJC are not the same thing at all. OBJC's nil is a real pointer to an empty object. But the nil here represents empty, but it is only a semantic concept, there are actual types, see nil What is Swift's what it is:

/// A Null Sentinel value. Get }  

nilActually just NilType a variable, and this variable is a getter. Swift gives us a document comment that tells us that it nil is actually just a null tag value. In fact, when we declare or assign a variable of a Optional, the ? syntax of the sugar is to declare one Optional<T> , and then look at the right side of the equal sign is not nil this tag value. If not, init(_ some: T) an enumeration is generated with the value of type T to the right of the equal sign .Some and assigned to the Optional variable, and if it is nil, it is assigned to the None enumeration.

So, the story behind optional is actually hidden by this little ? .

I think the Optional discussion here is almost there, there are three small questions to explain.

First of all, NilType this type is very special, it seems to be a built in type, I do not get any information about it now. My own reverse is a small white, now it seems that Swift's reverse difficulty is also relatively large, so NilType some of the actions can only be guessed. As for the nil variable of this NilType type, guess, it may be Optional.None a kind of multi-type performance, because first it does point to 0x0, and it is consistent with the content of Optional.none. But the details have yet to be excavated or published.

Second, Apple recommends that we use a so-called implicit method when unwrap, which is the way to unwrap:

3  if let n = num {      //hasa numelse  {    //  no num}

Finally, this implicit invocation is safe enough, and it seems that performance should also be optimized (a bit forgotten: As seems to be said), it is recommended to write this inference as much as possible when unwrap, while reducing the direct unwrap of this behavior.

The last problem is that Optional variables can also be optinal. Because Optional is the equivalent of a black box, you can know if there is anything in the box (through Logicvalue), or you can open the box (unwrap) to get something inside (the type of variable you want or the nil that represents nothing). Note that there is no rule here that restricts the amount of a Optional to be Optional again, such as the following is completely OK:

" Hi "         // {Some "Hi"}   var anotherstr:string?? = str  //{{Some "Hi"}}  

This is actually not a lot of doubt, very perfect two-layer Optional, use of the time is also a layer to untie the good. But if it's nil, it's a little awkward here ...

var str:string? = Nil  var anotherstr:string?? = Nil  

? What is that??! I see!!

The question mark and exclamation marks are now used in concepts that are not in the original OBJC. It's easy to say, but it's still a lot of mystery behind. The original usage is not said, here the new usage from shallow into deep one by one.

The first is ? :

    • ?Tags that are placed behind types as Optional types

This usage has been said above, is actually a Optional<T> grammatical sugar, automatically wrap the content behind the equal sign into Optional. Give a use case, no more say:

var num:int? = Nil        // Declare an Int's Optional and set it to why there is no   "Hello"// declare a string of Optional, and give it a strings  
    • ?Placed behind a Optional variable, indicating that the variable is judged and implicitly unwrap. For example
Foo?. SomeMethod ()  

compared to the general first judgment and then call, similar to the benefit of the judgment is once judged as nil or, yes. false , the statement does not continue to execute, but returns a nil directly. The above notation is equivalent to

if let Maybefoo = foo {      maybefoo.somemethod ()}

The value of this notation is that it can be chained, called the Optional Chaining, which avoids a lot of conditional branching and makes the code easier to read. Like what:

if let upper = john.residence?. Address?. Buildingidentifier ()? . uppercasestring {      println ("John ' s uppercase building identifier is \ (upper). " )}

Note that the last buildingIdentifier question mark is () followed, which represents the return value of the Optional object buildingIdentifier() .

    • ?Placed in front of the parentheses of the Protocol method of a optional to indicate whether the method can be called

This usage is equivalent to the judgment in the previous OBJC -respondsToSelector: , and if the object responds to this method, it is called. Example:

delegate?. Questionviewcontrollerdidgetresult? (self, result)  

A second question mark in the. Note that the above () question mark is not the same as above, here is the () previous, indicating the method of inquiry.

In fact, in Swift, the default potocol type is no optional method, because type safety can be ensured based on this premise. However, protocol in the COCOA framework has many optional methods, for these optional interface methods, or if you want to declare an interface with an optional method, you must precede the declaration with a keyword and precede the optional protocol @objc method @optional with a :

@objc protocol Counterdatasource {    ,     int    , intget  }} 

And then a ! summary of the new usage.

    • !Placed behind the Optional variable, which indicates a forced unwrap transformation:
Foo!. SomeMethod ()  

This will cause a Optional<T> quantity to be converted to T . However, it is important to note that if the amount of this Optional is nil, the conversion will cause the program to crash at run time. So in the direct write ! conversion must be very careful, only when there will be dead determination and full grasp of the ! strong turn. If the amount to be converted is nil, we'd better use if let the syntax to make a judgment and implicit conversion to ensure security.

    • !Placed behind a type that represents a forced implicit conversion.

In this case ? , the behavior that follows the type is similar, and is a type-declared syntax sugar. ?declares that Optional ! a type is actually declared ImplicitlyUnwrappedOptional . The first thing to be clear is that this type is one struct , where the key part is a value Optional<T> , and a set of getters and methods that take values from this value:

struct Implicitlyunwrappedoptional<t> : Logicvalue, reflectable {      var value:t?    // ...    Static Get }    static func Some (value:t), t!    // ...}

From the outside, actually this and Optional the variables are similar, there are Some None . In essence, it ImplicitlyUnwrappedOptional is a type of storage Optional that implements the Optional characteristics of external methods, and the only difference is that Optional we need to do unwrap manually (whether it's using var! or let if assigning, we do something), and will automatically go to unwrap at the time of use and invoke the subsequent operation without having to add a manual display/implicit operation.

Why do you design this? Mainly based on the OBJC of the COCOA framework of the two-point consideration and compromise.

The first is that there is a pointer to an empty object in the OBJC, which is what we are accustomed to nil . In Swift, in order to deal with OBJC's nil compatibility, we need a nullable amount. And because Swift is designed to create a completely type-safe language, we need type safety not only for class, but for other types of structures as well. So naturally, we can use Optional's emptiness to do the equivalent of OBJC. Because the COCOA framework has a large number of APIs that will return nil, we also need to replace them with a corresponding one that either represents the existence or does not exist when we use Swift to express them Optional .

Well, wouldn't that Optional be a direct use? Why do we have to make one ImplicitlyUnwrappedOptional ? Because of ease of use. If it's all packaged, we're going to have to Optional go around and get a lot of trouble calling many APIs. And for the ImplicitlyUnwrappedOptional compiler to do a lot of processing for us, so that we are sure that the return value or the value to be passed is not empty, it is very convenient to do not need to do any conversion, direct use. But for those Cocoa that might return nil, we would have to check the method, we should write if for conversion and check.

For example, the following notation will cause aEXC_BAD_INSTRUCTION

Let formatter = nsdateformatter ()  = formatter.datefromstring ("not_valid" )  = now.datebyaddingtimeinterval (5.0//  exc_bad_instruction  

Because the dateFromString return is one NSDate! , and our input in the original will cause a nil return, here we need to check before using now:

Let formatter = nsdateformatter ()  = formatter.datefromstring ("not_valid" )  if let Realnow = Now {      realnow.datebyaddingtimeinterval (5.0  Else  {    println ("badDate")}

This is similar to what was done in the OBJC era, or, in a more Swift way.

Let formatter = nsdateformatter ()  = formatter.datefromstring ("not_valid" )  = Now?. Datebyaddingtimeinterval (5.0)  

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.