?? operator in Swift
It is "nil coalescing operator" (also called "default operator"). a ?? b
is value of a
(i.e. a!
), unless a
is nil
, in which case it yields b
. I.e. if favouriteSnacks[person]
is missing, return assign "Candy Bar"
in its stead.
EDIT Technically can be interpreted as: (From Badar Al-Rasheed's Answer below)
let something = a != nil ? a! : b
let something = a ?? b
means
let something = a != nil ? a! : b
This:
let snackName = favoriteSnacks[person] ?? "Candy Bar"
Is equals this:
if favoriteSnacks[person] != nil {
let snackName = favoriteSnacks[person]
} else {
let snackName = "Candy Bar"
}
Explaining in words, if the let
statement fail to grab person
from favoriteSnacks
it will assigned Candy Bar to the snackName