Introduction to Swift (iv)--optional type (optionals) and assertion (assert)

Source: Internet
Author: User

What is an optional type?

First of all, in Swift, a variable of type string has a method called ToInt that can convert a string variable to an int type variable.

var"5"var intValue = stringValue.toInt();println("intvalue = \(intValue)")

After executing the above method, we get the strange result:

intvalue = Optional(5)

In fact, it can be found that the return value of the ToInt method is not an int, but an int? This is because Swift provides a new type called "Optional type" (Optionals). The optional types of string and int types are each string? and int?

Because not every string can be converted to an integer, that is, the execution

var intValue = stringValue.toInt();

This code of the time. Do not know the detailed value of Intvalue. Assuming that StringValue cannot be converted to an int type, the value of intvalue here is nil.

Unlike OC, nil is not a null pointer, nor is it limited to the object type, but the value of a variable that is arbitrarily an optional type is missing.

String? and int? Variable values such as the optional type can be nil. For example, execute the following code:

var"53d"var intValue = stringValue.toInt();println("intvalue = \(intValue)")

The result will be:

intvalue = nil
Optional types and implicitly optional types force an optional type to be unpacked

Suppose you want to use the converted variable value. Instead of appearing optional (XXX) Such a strange expression, you can use an exclamation mark (!

) operator. Forces the value inside the optional type variable to be used. This is called forced unpacking in Swift (forced unwrapping of the optional ' s value).

However, forcing an optional type with a value of nil results in an execution-time error. Therefore, use an exclamation mark (!

) operator to force an optional type variable to be unpacked. Be sure to ensure that the value of the optional type variable is not nil.

The following code explains the previous concepts in detail:

var"55"var"5d"var intValueNotNil = stringValue1.toInt();var intValueNil = stringValue2.toInt();println("intvalue1 = \(intValueNotNil!

)") //强制解封。正常执行println("intvalue2 = \(intValueNil!)") //强制解封,执行时错误。

Again, execution-time errors cannot be discovered by the compiler. Will cause the app to flash back directly. Therefore the correct forced solution scheme should be for example the following:

let unknownValue:Int? = 3//let unknownValue:Int?

= nilifnil{ println("value = \(unknownValue。)")}else{ println("value = \(unknownValue)"//不强制解封,直接打印nil}

Another point to note is that. An optional type must be assigned an initial value when defined. You cannot skip assigning an initial value in a way that is of type callout. Otherwise, a compilation error is generated.

Optional bindings

Swift is a simple language, and it is too cumbersome to use forced type marshaling to get the value of an optional type variable, a lot of people are reluctant to use. Therefore, the value in the optional type can be unpacked in a way that can be optionally bound.

let unknownValue:Int?=3//let unknownValue:Int? = nilifvarvariable= unknownValue {    println("variable = \(variable)")}

The key to an optional binding is the assignment statement in the IF inference. Suppose the value of Unknownvalue is nil,if inference is not true. Assuming that the value of Unknownvalue is not nil, then variable will get the value unknownvalue after it is unpacked. It is therefore no longer necessary to use exclamation marks when printing variable (!

) operator.

Implicitly-unpacked optional types

An implicitly-encapsulated optional type is an implicit optional type, and is a concept that is relative to an optional type. It needs to add an exclamation mark after the original base type. For example, the following code can define an implicit optional type:

var implicitOptional:Int! = 3

An implicitly selectable type indicates that the default value for this variable has always been (that is, not nil). The use of implicit optional types gives Swift the right to voluntarily unlock implicitly selectable types. No need to invoke exclamation mark (!

) operator to unlock an implicitly selectable type.

var implicitOptional:Int! = 3ifnil{    println("implicitOptional = \(implicitOptional)")}

Output Result:

implicitOptional = 3

It is important to note that an implicitly selectable type is actually an optional type. That is, assuming that the value of an implicitly selectable type is nil, execution-time errors (runtime error) are still triggered. So when using implicit optional type variables, for security reasons. Or should be inferred with an if statement.

Implicit optional types are not recommended in addition to the usage scenarios for implicit optional types that are mentioned in the following article when no master references are introduced. Simply replace with an optional type to

Implicit optional binding

An optional binding for an implicitly selectable type is called an implicit optional binding, and an optional binding of an optional type is fully consistent with the use.

It's just not necessary to study it carefully. The demo sample code is as follows:

varnil//var implicitOptional:Int! = 3ifvar unknownImplicitOptional = implicitOptional{    println("implicitOptional = \(unknownImplicitOptional)")}
Assertion

assertions, in fact, have nothing to do with the optional type, and its use can help program apes find and locate errors more easily. It is also not difficult to use, so it is put in the fourth chapter and finally introduced.

In Swift. Assert is implemented through the Assert function, where the first parameter is the inference condition and the second parameter prints when the condition is not satisfied .

let20assert(age > 20, "你是成年人啦!")

Assume that the assertion is triggered. Will force the end of the program and output the relevant information:

fileline45

Using assertions is very easy. However, a good habit of using Swift is to reasonably add assertions that help locate and troubleshoot bugs.

Appendix to the full column-"Swift easy access"

"Introduction to Swift (i)--basic syntax"
"Introduction to Swift (ii)--character and string"
"Introduction to Swift (iii)--tuples (tuple)"
"Introduction to Swift (iv)--optional type (optionals) and assert (Assert)"
"Getting Started with Swift (v)--Arrays (array)"
"Introduction to Swift (vi)--Dictionary (Dictionary)"
"Introduction to Swift (vii)-structure (struct)"
"Introduction to Swift (eight)--powerful redundancy operator"
"Introduction to Swift (ix)--string and int, Double, float and other numbers convert each other"
"Introduction to Swift (10)-circular reference, weak reference, and no master reference"
"Introduction to Swift (11)--type conversion with IS, as Operation"
"Introduction to Swift (12)--using extension to add Reverse output string method"

Introduction to Swift (iv)--optional type (optionals) and assertion (assert)

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.