Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Conditional Operator for nil/not nil

Tags:

ios

swift

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.

like image 702
slider Avatar asked Sep 12 '16 17:09

slider


People also ask

Does ternary operator check for NULL?

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.

How do you write 3 conditions in a ternary operator?

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.

What is nil-coalescing & ternary operator?

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.

Can ternary operator have two conditions?

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.


2 Answers

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
like image 122
rob mayoff Avatar answered Oct 22 '22 00:10

rob mayoff


  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

like image 33
Ketan Parmar Avatar answered Oct 21 '22 23:10

Ketan Parmar