Swift getting started (4) -- optional types (Optionals) and Assert, optionalsassert
What is an optional type?
First, let's take a look at the problem. In Swift, the String type variable has a method called toInt, which can convert the String type variable to the Int type variable.
var stringValue = "5"var intValue = stringValue.toInt();println("intvalue = \(intValue)")
After the above method is executed, a strange result is obtained:
intvalue = Optional(5)
In fact, we can find that the return value of the toInt method is not Int, but Int? This is because Swift provides a new type called Optionals. What are the optional types of the String and Int types? And Int?
Because not every string can be converted to an integer, that is
var intValue = stringValue.toInt();
When using this code, you do not know the specific value of intValue. If stringValue cannot be converted to the Int type, the intValue here is nil.
Different from OC, nil is not a null pointer and is not limited to the object type, but indicates that the value of any optional type variable is missing. String? And Int? And other optional types of variable values can be considered nil. For example, run the following code:
var stringValue = "53d"var intValue = stringValue.toInt();println("intvalue = \(intValue)")
The result is:
intvalue = nil
Optional type and implicit optional type forced unblocking optional type
If you want to use the converted variable value without any strange expression like Optional (xxx), you can use an exclamation point (!) Operator, which forces the use of values in optional type variables. This is called Forced unwrapping of the optional's value in Swift ).
However, forcing unblocking an optional type with a value of nil will cause a runtime error ). Therefore, the exclamation point (!) is used (!) Make sure that the value of the optional type variable is not nil.
The following code explains the previous concepts:
Var stringValue1 = "55" var stringValue2 = "5d" var intValueNotNil = stringValue1.toInt (); var intValueNil = struct (); println ("intvalue1 = \ (intValueNotNil !) ") // Force unblocking, normal operation of println (" intvalue2 = \ (intValueNil !) ") // Force unblocking, running error.
It should be reminded again that the runtime error cannot be detected by the compiler, which will cause the app to crash directly. Therefore, the correct forced unblocking solution should be as follows:
Let unknownValue: Int? = 3 // let unknownValue: Int? = Nilif unknownValue! = Nil {println ("value = \ (unknownValue !) ")} Else {println (" value = \ (unknownValue) ") // do not forcibly unseal and print nil directly}
Note that the initial value must be assigned to an optional type during definition. You cannot skip the initial value assignment using the type annotation. Otherwise, a compilation error occurs.
Optional binding
Swift is a concise language. It is too troublesome to use forced type unblocking to obtain values in optional type variables. Therefore, you can unseal values of the optional type by binding them.
let unknownValue:Int? = 3//let unknownValue:Int? = nilif var variable = unknownValue { println("variable = \(variable)")}
The key to the optional binding is the value assignment statement in the if judgment. If the value of unknownValue is nil, if judgment fails. If the value of unknownValue is not nil, variable will get the unknownValue value after unblocking. Therefore, you do not need to use an exclamation point (!) when printing variable (!) Operator.
Optional types of implicit unblocking
Implicit unblocking (optional type) is a concept relative to the optional type. It needs to add an exclamation point after the original base type. For example, the following code defines an implicit optional type:
var implicitOptional:Int! = 3
The optional implicit type indicates that the default variable has always had a value (that is, it is not nil ). Using the implicit type options gives Swift the right to automatically unseal the implicit type options without calling an exclamation point (!) You can use operators to unseal implicit optional types.
var implicitOptional:Int! = 3if implicitOptional != nil{ println("implicitOptional = \(implicitOptional)")}
Output result:
implicitOptional = 3
It should be noted that the implicit optional type is actually an optional type. That is to say, if the value of the implicit optional type is nil, a Runtime Error will still be triggered ). Therefore, when using implicit optional variables, the if statement should be used for security purposes.
In addition to the usage scenarios of the implicit optional type mentioned in the following section, we do not recommend that you use the implicit optional type. Replace the optional type directly.
Implicit binding
The optional binding of the implicit type is called the implicit binding, which is exactly the same as the optional binding of the optional type. However, there is no need to study it carefully. The sample code is as follows:
var implicitOptional:Int! = nil//var implicitOptional:Int! = 3if var unknownImplicitOptional = implicitOptional{ println("implicitOptional = \(unknownImplicitOptional)")}
Assertions
Assertions are actually irrelevant to the optional type. They can help programmers easily find and locate errors, and are not difficult to use. Therefore, they are introduced at the end of chapter 4.
In Swift, assert functions are used to implement assertions. The first parameter is the judgment condition, and the second parameter is the condition.Not satisfied.
Let age = 20 assert (age> 20, "you are an adult! ")
If an assertion is triggered, the program is forcibly terminated and related information is output:
Assertion failed: you are an adult! : File/Users/KT/Desktop/MyIOS/Swift exercises/Swift -- optional type/main. swift, line 45 (lldb)
It is very simple to use assertions, but adding assertions reasonably helps to locate and eliminate bugs. It is a good habit to use Swift.
Appendix Swift getting started series tutorials Swift getting started (1) -- basic syntax Swift getting started (2) -- character and string Swift getting started (3) -- tuples (Tuple)
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.