I can use the ternary conditional operator for an if {} else {}
statement like this: a ? x : y
, or question ? answer1 : answer2
.
Is it possible to use this format to check if, instead of whether a
is true
or false
, a == nil
or a != nil
?
UPDATE: This was arguably the biggest brain fart of my career.
Ternary Operator checks whether the value is true, but Null coalescing operator checks if the value is not null. If there is more iteration to be executed, null coalescing operator found to be faster than the ternary operator. Null coalescing operator gives better readability as well comparatively.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
The nil-coalescing and ternary conditional operators are what's known as syntatic sugar. They sugar-coat verbose code in more concise code, and make your Swift code more readable.
In the above syntax, we have tested 2 conditions in a single statement using the ternary operator. In the syntax, if condition1 is incorrect then Expression3 will be executed else if condition1 is correct then the output depends on the condition2.
You can do this:
(a == nil) ? x : y
(Parentheses are not required but may make the code clearer.)
You can do this if you want something more confusing:
a.map { _ in x } ?? y
a != nil ? a! : b
The code above uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil, and to return b otherwise. The nil coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.
example :
let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"
Reference : Apple documentation
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