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

Source: Internet
Author: User

What is an optional type?

First of all, there is a problem with a string type variable in Swift that has a method called ToInt that converts 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 that correspond to the string and int types are string, respectively? and int?

Because not every string can be converted to an integer, which means that the

var intValue = stringValue.toInt();

This code, I do not know the specific value of intvalue. If StringValue cannot be converted to an int type, then the value of intvalue here is nil.

Unlike OC, nil is not a null pointer, nor is it limited to the object type, and the value of any variable that represents 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

If you want to use the converted variable values without a strange representation such as optional (XXX), you can use an exclamation point (! ) operator, forcing 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 a run-time error. Therefore, use an exclamation mark (! ) operator to force an optional type variable to be marshaled, make sure 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, a run-time error cannot be discovered by the compiler, causing the app to flash directly. So the correct mandatory solution should be as follows:

let unknownValue:Int? = 3//let unknownValue:Int? = nilifnil{    println("value = \(unknownValue!)")}else{    println("value = \(unknownValue)"//不强制解封,直接打印nil}

It is also important to note that an optional type must be assigned an initial value when defined. You cannot skip assigning an initial value in the same way as a type callout, or a compilation error will occur.

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, which many people do not want to use. Therefore, the values in the optional type can be unpacked by an optional binding.

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 judgment. If the value of Unknownvalue is nil,if judgment is not established. If the value of Unknownvalue is not nil, then variable will get the value of unknownvalue, so it is no longer necessary to use an exclamation mark 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 automatically unlock implicitly selectable types without the need to invoke an 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 the implicit optional type is actually an optional type, that is, if the value of the implicitly selectable type is nil, a run-time error will still be triggered. Therefore, if you use an implicit optional type variable, you should use the IF statement for security purposes.

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. Replace with optional type directly

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 exactly the same as the use. But there is no need to study it carefully. The sample code is as follows:

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

Assertions are in fact unrelated to the optional type, and its use can help programmers find and locate errors easily, and it is not difficult to use them, so they are presented at the end of the fourth chapter.

In Swift, assertions are implemented through the Assert function, where the first parameter is the judging condition and the second parameter is the printing information when the condition is not satisfied .

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

If the assertion is triggered, the program is forced to close, and the relevant information is output:

fileline45

Using assertions is simple, but adding assertions reasonably, helping to locate and troubleshoot bugs, is a good habit in using Swift.

Introduction to Swift Introductory Series Swift Introduction (i)--Basic Syntax Swift Introduction (ii)--character and string introduction to Swift (c)--tuple (tuple)

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

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.