[Swift] Optional type

Source: Internet
Author: User

Optional type

The 2nd chapter of Swift's authoritative guide--swift the Language Foundation, and this chapter selects the most basic features of the swift language. Although these features represent only a small fraction of the full features of swift, they are essential for all swift programs. So, by learning from this chapter, readers can use Swift to write the most basic programs and to be deeply shocked by the new features that Swift offers. This section introduces you to optional types.

AD:

2.6 Optional types

The optional type is also a newly added object in the swift language. The main purpose is to solve the case where the object variable or constant is empty. The variables and constants defined earlier cannot be null. There must be a value inside.

The optional type in Swift allows the variable (constant) to have no value (set to nil). It is important to note that nil in Swift is not the same as nil in objective-c. The nil of the former means no value, while the latter's nil indicates that the value of the variable is null.

Optional types require a question mark (?) to be appended to the type. A typical example is that the string class has a ToInt method that converts the string to an int type. However, there is a problem here, the string may contain non-numeric characters, then the conversion fails. If the error catch is not added in other languages, an exception may be thrown, whereas in Swift, if the conversion fails, it returns nil directly. Represents a value that does not return an int type (you do not want to add a catch exception anyway, because there is no exception catch in Swift). The ToInt method here returns an optional type.

The following code converts the value in Numstr to a value of type int and outputs the value.

    1. var numstr:string = "123"
    2. var value:int?  = Numstr.toint (); Value must be defined as an optional int type, otherwise it will not compile successfully
    3. println (value)

If you change 123 to a value that will cause the conversion to fail, such as A123, then the above code will output nil.

For a variable or constant of an optional type, it is usually necessary to make a judgment before use, for example, the following code will judge value, and if it does succeed (not nil), output a line of text.

    1. if Value! = Nil
    2. {
    3. println ("Conversion succeeded")
    4. }

However, it is cumbersome to judge every time the value variable is used, so Swift adds an exclamation point (!) that determines the value of an optional type variable. After the first judgment on value, if you can confirm that the variable has been assigned a value, you can then add an exclamation point directly after value to use the variable.

    1. println (value!)

If you add an exclamation mark after an optional type variable (constant), the program breaks when the variable (constant) is nil, and outputs the following information at the terminal.

    1. Fatal error:unexpectedly found nil while unwrapping an Optional value

So when you add an exclamation mark after an optional variable (constant), make sure that the variable (constant) has a value.

It is now known that when you reference an optional type variable (constant), the exclamation mark is followed to throw a run-time exception when there is no value (nil) in the variable (constant). It's also a hassle to add exclamation points every time, so simply change the question mark to an exclamation point when defining an optional type variable (constant) so that you can reference these optional type variables and constants directly.

    1. var numstr:string = "123"
    2. var value:int!  = Numstr.toint (); Value must be defined as an optional int type, otherwise it will not compile successfully
    3. Even if value is not added! (of course, plus!), throws an exception when value is nil
    4. println (value)

Note When you use optional type variables (constants), if you use a question mark (?) to define and use these variables and constants separately, you can do so without an exclamation point (!). But to let these variables and constants and other values operate through the operator, it is necessary to add an exclamation point. As the following code is legal.

    1. var numstr:string = "123"
    2. var value:int! = Numstr.toint ();
    3. println (value)//If value is nil, nil is output

However, the following code will not compile successfully.

    1. var numstr:string = "123"
    2. var value:int! = Numstr.toint ();
    3. println (value + 4)//compilation failed, value must be written as value!, or use "!" when defining value

[Swift] Optional type

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.