Wrapping optional object

Hi everybody,
I’d like to understand the difference between
(objectname?.description)!
and
objectname!.description
Thank you in advance
Carola

Hi @caropere,
When you use object?.property you may get a nil and the variable that will hold the value would be an optional. This is useful if you are uncertain about the value of object, which could be nil.

However when you use object!.property you are saying that you want a value not an optional and are certain that the object is not nil. If the object is nil, the code will crash.

so you use ? to have lesser chances of crashes in comparison to the !. You would see that the ! is used with variables that generally refer to UI elements setup from the storyboard , because you generally would expect them to be present.

if you are writing code to check, a good way is to check the value

 if let someVar = object {
    someVar.property  // do what you want here
 }

you could also use a guard but then that has some complexities of its own.

cheers,

Hi @jayantvarma,
thank u! I understand perfectly optional type and wrapping it when you’re sure the value is not nil, but I don’t understand if these two wrapping methods are exactly the same:
(objectname?.description)!
and
objectname!.description
thanks a million

hi @caropere,

the answer to your specific question, is that both are the same, i.e. they will not be optionals and unwrapped.

If the objectname is nil, then both will crash - if you understand the difference between Implicitly Unwrapped Optionals and Optionals then I would suggest you try this in Playgrounds and see.

cheers,

This topic was automatically closed after 166 days. New replies are no longer allowed.