Aryan Aryan - 4 years ago 169
Swift Question

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

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 attachment: NSTextAttachment = NSTextAttachment()
attachment.image = UIImage(named: "placeholder.png")
attachment.image!.size ... // or attachment.image?.size ...

What's the difference between

Answer Source

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 if it'll 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download