Swift: Optional type (Optional)

Source: Internet
Author: User
Tags closure

when we use OBJECTIVE-C to represent string information, we can write it in the following way .

NSString *str = @ "Autumn hates snow"; str = nil;

because Objective-c is a weakly typed language, the str here can be either a specific string or nil. But in swift it is not possible, because Swift is a type-safe language, a variable of type string cannot be either a specific string, or nil (more strictly the string type of content only). Therefore, the concept of optional types is available in Swift. (This concept is also "borrowed" from other programming languages, such as C #, but is called a nullable type in C #)

I. Definition of an optional type

Format of the optional type: type name?

For example:

var phone:string?
The question mark "?" indicates that the value of the phone is optional, may be a string, or it may not exist.

The value of the phone is either a string type or nil.

Second, the optional type of application

String has a ToInt method that converts a string to a corresponding integer.

Some strings can be converted to integers: "123", for example, can be converted to 123.

Some strings cannot be converted to integers, such as "Autumn-hate snow", and cannot be converted into integers.

So the return value of the ToInt method is an optional int type (that is, int?).

So the conversion results are as follows:

Let num = "123". ToInt ()      //123let num2 = "Autumn Hate Snow". ToInt ()   //Nil
Note: Num and num2 are both int? type, not int type.

Iii. Nature of optional types

Int? is actually a layer of the int wrapper, they are two different data types.

var num:int? = 10
It can be understood that NUM contains both "Some" and "None" properties, and the above operation simply wraps 10 of the int type into the "Some" in int?. as follows:


Iv. forced unpacking (unpacking)

Add an exclamation mark "!" after the optional type, and you can assign the value of the optional type (wrapper) to the specific type.

For example, the following wording:

var num:int? = 10var Numvalue:int = num!
in fact, the value of "Some" is taken out. as follows:


Note: If the value of the optional type (wrapper) does not exist, that is, the value of "Some" does not exist, and the forced unpacking will be an error.

var Num:int?var numvalue:int = num!

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

Therefore, be sure to check that the value of the optional type (wrapper) exists before forcing the package.

for the above scenario, we can use the IF statement to detect whether a value of an optional type (wrapper) exists. For example:

If let num = "156". ToInt () {    println ("num's value is \ (num)")} else {    println ("Num's value does not exist")}

v. Implicit unpacking (Unpacking)

By default, if you want to assign the value of an optional type (wrapper) to a specific type, such as assigning an int value to an int type, you need to use an exclamation mark "!"

If an optional type is declared as an implicit unpacking.

1. No more forced unpacking.

2. Ability to automatically unpack: the value of the optional type (package) is automatically removed to assign to the specific type.

The declaration of an implicit unpacking simply changes the "?" to "!". For example:

var num:int! = 20var Numvalue:int = num//automatic unpacking
the principle of implicit unpacking:

1. The equivalent of telling the compiler that the value of this optional type is always present and that it is absolutely possible to take out the value inside.

2. Do not manually add the exclamation mark "!" in the value, the compiler will automatically add an exclamation mark "!".

Six, "?" and "!" Usage scenarios

1. Closures in Swift (if in doubt, please refer to my previous section,Swift: Closures (Closures)) has replaced block, defining a closure:

var testclosure: ((str1:string)-Void)?

as you can see, there is a question mark "?" Behind the type of closure, because the closure property is likely to be nil.


2. The Iboutlet connection operation in Swift indicates that the control is certain to exist. For example:

@IBOutlet weak var testlabel:uilabel!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Swift: Optional type (Optional)

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.