First of all, you have to understand the concept of Optional
, from Apple Docs:
A type that represents either a wrapped value or nil
, the absence of a value.
So if the Optional
variable has a value of that type that can be unwrapped, it contains that value. If it doesn't, it contains nil
.
Let's say you have the following code:
let string: String? = "dog"
As you can see, an optional String
has been created, using the optional operator ?
. If you now try to print it:
print(string)
the output will be: Optional("dog")
. That is because this optional string has not been unwrapped. A way to unwrap it is using the if-let
pair, as below:
if let string = string{ print(string) }
This will now output dog
. But why? - When you declare a let
constant in the structure of an if
-statement, a copy of the original value is created, and if the value was previously nil
, then the if
-statement doesn't execute at all, because the condition will be false
. So you are guaranteed that if the code inside the if let
statement executes, then the newly-created constant will contain the successfully unwrapped value of the original variable.
"I am a bit confused here. Are these two errorDescription
the same?"
No, they are not. They just happen to have the same name. You can choose any other name for the newly created constant.
Now that this things are clear, there is one more thing to be explained. When using the let
constant declared in the if-condition, you refer to it as: value
. When one wants to access the original optional (inside the if
), it is referred as: self.value!
.
There are other ways to unwrap an optional as well:
guard let
statements - should only be used inside functions or loops
if value != nil{}
+ force-unwrapping, because you are certain that the value is not nil.
You can learn more about Optionals at The Swift Programming Language (Swift 3.1): The Basics