In Swift Language Tutorial for Beginner 4 - Tuple, we look at the tuple type in Swift, and this time we’ll learn about another special optional data in Swift - optional.
Optional
Optional is designed to help programmers deal with common null pointer errors. There is no similar language mechanism in C/C++, and the Java language began to provide an Optional type in Java 8, similar to this. But the syntax in Swift is simpler.
To understand optional, we need firstly understand null values in Swift.
In Swift, a variable (regardless of its type) can be represented by “nil” if it has no value. However, by default, the variables we define with the “var” keyword must be assigned initial values before they can be used, otherwise the compiler will report an error, such as:
1 | var myName: String |
The above code cannot be compiled, but it is correct if the initial value is assigned.
1 | // var myName = "tom" |
But what if a variable just has no value in some cases, i.e. the variable is allowed to be nil (nil is not a pointer - it is a definite value, which is used to indicate that the value is missing) This is where the optional version is needed.
Define an optional variable
In swift, declaring optionality is as simple as adding a “? Let’s modify the above example:
1 | var myName: String? |
The code can now be compiled, but there are still warnings. Because for optional variables, it is risky to access its value directly (there may be no value).
Access the value of an optional variable
To eliminate the warning (which, of course, also tells us that there may be a potential problem with the program), to access the value of an optional variable, you need to first determine whether its value is empty, and then access it with the “!” operator, which is written like this:
1 | var myName:String? = "tom" |
Of course, it is also possible to assign a value
1 | var myName:String? = "tom" |
This is a hassle to write, so Swift equals a special if statement, such as the example above, which can be written like this:
1 | var myName:String? = "tom" |
Direct judgment and assignment, so that the “!” sign is no longer used when using it.
This expression can also include the case where the variable value is empty, or the example above:
1 | var myName:String? |
The if statement can also include multiple optional variables and logical judgments at the same time, separated by a “,” sign between expressions, such as:
1 | var obj1:Int? = 1 |
Next
Next, we’ll take a brief look at collection types in Swift. Swift Language Tutorial for Beginner 6 - Array