Operators are symbols that check, change or combine values.
In this article, we’ll go over the two most confusing Swift operators, the double question mark (??) nil-coalescing operator and the ternary condition operator (= ? a : b).
The nil coalescing operator looks like double question marks ??
. It’s basically short hand for this block of code:
if userInput != nil {
return userInput!
} else {
return "default"
}
So we can use the nil coalescing operating to make this function into one line and assign the returned value:
let x = userInput ?? "default"
This means x
will get the value of userInput
only if it is not nil, otherwise it will get the value "default"
. This operator is used often in Swift to work with optionals without having to write if statements all the time.
The ternary conditional operator is a short hand technique used to simplify this block of code:
if condition {
return "a"
} else {
return "b"
}
With the ternary conditional operator we can do this:
let x = condition ? "a" : "b"
This above code says to assign “a” to x
if condition
is true, otherwise assign “b”.
Super slick right? Ternary conditional operators are like one line if statements.
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.