What is difference between "?" and "!" in Swift?

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


what is ! and ?:

  • Use ? if the value can become nil in the future, so that you test for this.
  • Use ! if it really shouldn't become nil in the future, but it needs to be nil initially.

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.

Tags:

Swift