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
?
The difference between == and === in Swift is: == checks if two values are equal. === checks if two objects refer to the same object.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With