“You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.”
This quote is from “The Swift Programming Language (Swift 5.2)”. Books
And that’s the easiest and perfect explanation in my opinion. Here I’m gonna explain those a little bit deeper. Grab a cup of coffee and enjoy ☕️
Optional is a type of some value that can provide but doesn’t have to. For that, you use a “?” at the end of the type. For example:
Maybe let’s see some more complex examples where we can actually see how it works.
Here we are creating some server response Integer with a value of 404. Then we want to print to the console this value. We can see that the console is telling us that this value is optional. But when we set the "serverResponseCode" to nil, then we get nil. It might be a scenario where we want to get some data from the user and we won’t get that for some reason. If we won’t use an optional here then our code for sure will crash.
Let’s edit our code a little bit:
Now I used “!” to unwrap the value of serverResponseCode and it forced me to get a value. But if I would use “!” in the second print then Xcode will give an error because there is no value.
But there is another way to fix this.
You can use “??” to put other values if there is no value from the user. This print checks if there is a value of serverResponseCode then it will print it, otherwise, we will get 500 as a result of this line.
It is really easy if you practice optionals a little. They are very useful when you want to avoid errors and crashes 😄
Comments
Post a Comment