I know what \"?\" and \"!\" mean when I declare variables in Swift. But what do they mean when using these variables? For example, in this code:
var
When you are using !
and the variable is nil
it will trigger run time error but if use ?
it will fail gracefully.
More detail information in apple document
Both symbols ! and ? used for optionals. We should have to use !, when we make sure option type variable has value at a time and we need to take action on it.Otherwise It will crash if variable value is nil.And if you are using ?, Application will not crash in nil case.
You can follow this link for more information:- https://www.youtube.com/watch?v=twBfiKsbHP8
what is ! and ?:
if You are using attachment.image!.size
any variable with ! means, compiler don't bother about that variable has any value or nil
.
it goes to take action further, it will here try to get size of image. if attachment.image
is nil
then app will be crash here.
While, attachment.image?.size
, this will make sure you, if attachment.image
isn't nil then further action will be take place, otherwise But it confirm Application will not be crash in case of nil
value of image
.
Summary:
We should have to use !, when we make sure option type variable has value at a time and we need to take action on it further, Otherwise.
Use attachment.image!.size
if you're guaranteed that image?
isn't nil
. If you're wrong (and it is nil
) your app will crash. This is called forced unwrapping.
If you're not sure it won't be nil
, use image?
.
In your case image!
is OK, since you control whether placeholder.png
exists.
Read all of the documentation on Swift Optionals. It's a basic and fundamental part of the language.