When defining a variable/constant in Swift, there is a different concept than in OC: optional. The point of an optional definition is to tell the editor that the variable can have a value or be null.
First: optional packaging and forced unpacking.
Representation:
The above can be called wrapped
It can be called unwrapped when called
Where: the default options for constants and variables are different.
Default optional constants: none
Optional variable: nil
An initial value can only be initialized once, whether it is a constant or a variable!! , and constants cannot be assigned (assigned after initialization).
When you force unpack, if it’s nil, it crashes. Because nil doesn’t work.
Second:?? Simple three-purpose use
In order to solve the problem of a crash during forced unpacking, we usually have to determine whether the object is empty or not, but this defeats the purpose of Swift and makes the code extremely redundant if we decide on each one.
So, what’s the solution? Swift has a?? Operation, which is a simple triplet that says if it’s nil, if it’s not nil, use the original value, otherwise?? The value we set to it later.
The following ๐ :
Third: no forced unpacking
Although using?? Code that makes the decision easier, but still has operations. And then there’s another operator in Swift, iflet/var, which just does a little bit of checking, if it’s not nil, to go inside the execution braces and execute the code. This eliminates unnecessary code.
The following ๐ :
Finally: To be more in line with our development habits, Swift has introduced Guardlet, which is the same as iflet but the opposite in structure. One is that one of the variables that goes into the execution is nil, and two is that the scope of the variable is a higher level if it’s not nil.
The following ๐ :
PS: Iflet and Guardlet are especially frequently used in unpacking. Again, one small detail, naming, in general, we use the same name, so there’s less renaming, and everything else stays the same.
The following ๐ :