What is difference between ? and ! in Swift?
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.
what is the difference between ? and ! operator in swift?
An optional type can be nil
var nameOfToy: String?
The toy may have a name;
nameOfToy = "Buzz"
so
print (nameOfToy!)
is Buzz.
The question mark indicates that it is optional, i.e. can be nil, so you have to UNWRAP it with the !. This is because the variable is optional.
But what happens if there is no name of a toy, and you use !. In this case you get a nasty crash.
Swift : Difference in '!' and '?' in swift
There are two types of variables in Swift.
- Optional Variables
- Normal(Non-Optional) Variables
Optional Variables:
The shortest description is Optional variables/objects contains the the property "object-returns-nil-when-non-exist". In objC almost all the object we create is optional variable only. That is the objects has the property "object-returns-nil-when-non-exist" behavior. However, this particular behavior is not needed all the time. So, to identify the optionals the symbols '?' and '!' has been used. Again there are two type of optionals...
- Normal Optionals(?)
- Implicitly unwrapped optionals(!)
Normal optionals:
var normalOptional : String?
Implicitly unwrapped optionals:
var specialOptional : String!
Both are having the "optional" behaviour, but the difference is the 'Implicitly unwrapped optional' can also be used as a normal(non-optional) value.
For instance, the indexPath variable is declared in the function(cellForRowAtIndex) parameter list by default tableview delegate methods. The row value exists when the cellForRowAtIndex is get called. There, the indexPath variable is declared in the function(cellForRowAtIndex) parameter list.
So, the unwrapping of 'row' value from 'indexPath' is as follows.
var rowValue = indexPath?.row // variable rowValue inferred as optional Int value
or
var rowValue = indexPath!.row// variable rowValue inferred as normal Int value
Note: When using the '!' unwrapping, have to be very sure that the particular class exists(contains value).
Hope this link will gives you more idea. What is the intended use of optional variable/constant in swift
Difference Between ? and ! in Swift Language?
As per the official Apple docs:
When working with optional values, you can write ? before operations
like methods, properties, and subscripting. If the value before the ?
is nil, everything after the ? is ignored and the value of the whole
expression is nil. Otherwise, the optional value is unwrapped, and
everything after the ? acts on the unwrapped value. In both cases, the
value of the whole expression is an optional value.Once you’re sure that the optional does contain a value, you can
access its underlying value by adding an exclamation mark (!) to the
end of the optional’s name. The exclamation mark effectively says, “I
know that this optional definitely has a value; please use it.” This
is known as forced unwrapping of the optional’s value (...)
Apple Inc. 'The Swift Programming Language'. iBooks. https://itun.es/nl/jEUH0.l
What does an exclamation mark mean in the Swift language?
What does it mean to "unwrap the instance"? Why is it necessary?
As far as I can work out (this is very new to me, too)...
The term "wrapped" implies we should think of an Optional variable as a present, wrapped in shiny paper, which might (sadly!) be empty.
When "wrapped", the value of an Optional variable is an enum with two possible values (a little like a Boolean). This enum describes whether the variable holds a value (Some(T)
), or not (None
).
If there is a value, this can be obtained by "unwrapping" the variable (obtaining the T
from Some(T)
).
How is
john!.apartment = number73
different fromjohn.apartment = number73
? (Paraphrased)
If you write the name of an Optional variable (eg text john
, without the !
), this refers to the "wrapped" enum (Some/None), not the value itself (T). So john
isn't an instance of Person
, and it doesn't have an apartment
member:
john.apartment
// 'Person?' does not have a member named 'apartment'
The actual Person
value can be unwrapped in various ways:
- "forced unwrapping":
john!
(gives thePerson
value if it exists, runtime error if it is nil) - "optional binding":
if let p = john { println(p) }
(executes theprintln
if the value exists) - "optional chaining":
john?.learnAboutSwift()
(executes this made-up method if the value exists)
I guess you choose one of these ways to unwrap, depending upon what should happen in the nil case, and how likely that is. This language design forces the nil case to be handled explicitly, which I suppose improves safety over Obj-C (where it is easy to forget to handle the nil case).
Update:
The exclamation mark is also used in the syntax for declaring "Implicitly Unwrapped Optionals".
In the examples so far, the john
variable has been declared as var john:Person?
, and it is an Optional. If you want the actual value of that variable, you must unwrap it, using one of the three methods above.
If it were declared as var john:Person!
instead, the variable would be an Implicitly Unwrapped Optional (see the section with this heading in Apple's book). There is no need to unwrap this kind of variable when accessing the value, and john
can be used without additional syntax. But Apple's book says:
Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.
Update 2:
The article "Interesting Swift Features" by Mike Ash gives some motivation for optional types. I think it is great, clear writing.
Update 3:
Another useful article about the implicitly unwrapped optional use for the exclamation mark: "Swift and the Last Mile" by Chris Adamson. The article explains that this is a pragmatic measure by Apple used to declare the types used by their Objective-C frameworks which might contain nil. Declaring a type as optional (using ?
) or implicitly unwrapped (using !
) is "a tradeoff between safety and convenience". In the examples given in the article, Apple have chosen to declare the types as implicitly unwrapped, making the calling code more convenient, but less safe.
Perhaps Apple might comb through their frameworks in the future, removing the uncertainty of implicitly unwrapped ("probably never nil") parameters and replacing them with optional ("certainly could be nil in particular [hopefully, documented!] circumstances") or standard non-optional ("is never nil") declarations, based on the exact behaviour of their Objective-C code.
What is difference between '&' and ',' in swift about Protocol Composition
From the Swift documentation on protocols, I think &
is mainly used when you are requiring a variable to adopt to multiple protocols, ex:
func wishHappyBirthday(to celebrator: Named & Aged) {
print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")
}
And you use ,
when you want to adopt a custom struct/class to multiple protocols:
struct SomeStructure: FirstProtocol, AnotherProtocol {
// structure definition goes here
}
Difference between == and ===
In short:
==
operator checks if their instance values are equal, "equal to"
===
operator checks if the references point the same instance, "identical to"
Long Answer:
Classes are reference types, it is possible for multiple constants and variables to refer to the same single instance of a class behind the scenes. Class references stay in Run Time Stack (RTS) and their instances stay in Heap area of Memory. When you control equality with ==
it means if their instances are equal to each other. It doesn't need to be same instance to be equal. For this you need to provide a equality criteria to your custom class. By default, custom classes and structures do not receive a default implementation of the equivalence operators, known as the “equal to” operator ==
and “not equal to” operator !=
. To do this your custom class needs to conform Equatable
protocol and it's static func == (lhs:, rhs:) -> Bool
function
Let's look at example:
class Person : Equatable {
let ssn: Int
let name: String
init(ssn: Int, name: String) {
self.ssn = ssn
self.name = name
}
static func == (lhs: Person, rhs: Person) -> Bool {
return lhs.ssn == rhs.ssn
}
}
P.S.:
Since ssn(social security number) is a unique number, you don't need to compare if their name are equal or not.
let person1 = Person(ssn: 5, name: "Bob")
let person2 = Person(ssn: 5, name: "Bob")
if person1 == person2 {
print("the two instances are equal!")
}
Although person1 and person2 references point two different instances in Heap area, their instances are equal because their ssn numbers are equal. So the output will be the two instance are equal!
if person1 === person2 {
//It does not enter here
} else {
print("the two instances are not identical!")
}
===
operator checks if the references point the same instance, "identical to"
. Since person1 and person2 have two different instance in Heap area, they are not identical and the output the two instance are not identical!
let person3 = person1
P.S:
Classes are reference types and person1's reference is copied to person3 with this assignment operation, thus both references point the same instance in Heap area.
if person3 === person1 {
print("the two instances are identical!")
}
They are identical and the output will be the two instances are identical!
Related Topics
Swift Mutable Set: Duplicate Element Found
Swift- Variable Not Initialized Before Use (But It's Not Used)
Why Is It Legal to Mutate an Actor's Nonsendable Property
Turn for in Loops Local Variables into Mutable Variables
Swiftui Out of Index When Deleting an Array Element in Foreach
Swift Switch Statement Considered All Cases of Int, But Compiler Still Display Error
Call External Function Using Watchkit Force Touch Menuitem
A Switch Bug in Swift? - "Switch Must Be Exhaustive, Consider Adding a Default Clause."
Firebase Uid VS Document-Id and Firestore Rules
How to Declare Swift Implicitly Unwrapped Optional as a Constant
How to Use Println in Swift to Format Number
How to Destroy a Singleton in Swift
Convert Date to Integer in Swift
How to Debug "Precondition Failure" in Xcode