Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 attachment.image!.size and attachment.image?.size?

like image 494
Aryan Avatar asked Sep 17 '14 15:09

Aryan


People also ask

What is the difference between == and === in Swift?

The difference between == and === in Swift is: == checks if two values are equal. === checks if two objects refer to the same object.

What is difference between as As and As in Swift?

Type casting in Swift is implemented with the is and as operators. is is used to check the type of a value whereas as is used to cast a value to a different type.

What does colon mean in Swift?

The colon in the declaration means “…of type…,” so the code above can be read as: “Declare a variable called welcomeMessage that's of type String .” The phrase “of type String ” means “can store any String value.” Think of it as meaning “the type of thing” (or “the kind of thing”) that can be stored.

What is the difference between let and where in Swift?

Let is an immutable variable, meaning that it cannot be changed, other languages call this a constant. In C++ it you can define it as const. Var is a mutable variable, meaning that it can be changed. In C++ (2011 version update), it is the same as using auto, though swift allows for more flexibility in the usage.


1 Answers

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.

like image 74
Aaron Brager Avatar answered Oct 05 '22 05:10

Aaron Brager