Well, reading The Swift Programming Language - The Basics I came across the topic of optionals
, something that I'm already getting the hang of, but not quite yet. The doubt is the next one:
Why use a implicit optional
instead of a normal variable?
If after all, I'm going to have to be careful that this variable is not nil
when I use it with !
.
If an implicitly unwrapped optional is nil and you try to access its wrapped value, you'll trigger a runtime error. The result is exactly the same as if you place an exclamation mark after a normal optional that does not contain a value.
Example code:
let possibleString: String? = "An optional string."
let forcedString: String = possibleString!
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString
In this case, if any variable is nil
and I do the unwrapping (implicit or explicit) it would give an error, so... What is the use of the implicit optional for?
I must be misunderstanding, I'm not doing so well with English and I do my best to understand but well.
They are very useful as well as important. In your examples, there is something wrong.
This doesn't make sense, since if you assign a value to it when declaring the variable, the variable is no longer
Optional
. That is, a correct form would be:(remember that types are inferred, and try to avoid making them explicit if possible)
To exemplify the importance/usefulness of them,
Optionals
look at the following case. Imagine that you have a manager to download contacts like the one below:Well, on the other hand, you have a
UIViewController
where you want to display those contacts. By instantiating it, you download the new contacts from a given date. The code would be:Well, if you notice I have two properties, one
Optional
and the other not. In the case of the date, we initialize it ininit
and therefore it will always have a value. We can also initialize it directly like so, but it is a matter of preferences:On the other hand, we have the property
contacts
that isOptional
. This allows us to make sure there are contacts to display. When enteringUIViewController
we call the contact download function, if this function does not find any contact on the server, it returns aOptional
and therefore I can act accordingly (in this case I show a message or an error). If it returned any result, it would save it in the variablecontacts
and use it later.From here on, it is a matter of playing with
if let
orguard else
to ensure that there is some value or not and avoid errors at runtime.Change the code to the following and run it
Now you will see what The Swift Programming Language - The Basics is talking about