Swift Ternary (?:) Operator

  Total Views : 349
  Comments : 0
  Keywords : Swift ternary operator is used to replace if else statement with example, Swift ternary operator is a shortcut way to perform same if else statement operation with example

Here we will learn ternary operator in swift with examples and how to use ternary operator as an alternative of if else statement with examples.

Swift Ternary (?:) Operator

In swift, ternary operator will perform same operation whatever is performed by if else statement but it’s a shortcut method to perform if else statement operation.

 

Now we will see the functionality of ternary operator in swift programming language using algorithm diagram.

Swift Ternary Operator Flow Diagram

Following is the swift ternary operator flow diagram to represent how the functionality of ternary operator will work in swift programming language.

 

Swift Ternary Operator Flowchart Diagram with Examples

 

If you observe above swift Ternary operator flow diagram first it will evaluates the given condition is TRUE or FALSE. If given condition is TRUE then it will execute the code block within if statement. In case the given condition is FLASE then it will execute else condition code block and reach the end of statement.

Syntax of Swift Ternary Operator

Following is the syntax of ternary operator in swift programming language.

 

condition ? true_expression : false_expression

If you observe above swift ternary operator syntax if given condition is TRUE then it will return first true_expression value otherwise it will return false_expression value.

 

Now we will see how to use ternary operator in swift programming language with examples.

Swift Ternary Operator (?:) Example

Following is the simple example using ternary operator in swift to check the condition before execute the expressions within the condition.

 

let x = 10

let y = 20

 

let result = (x>y) ? ("x is greater than y") : ("y is greater than x")

print(result)

If you observe above swift ternary operator example we are checking condition that whether “x” value greater than “y” or not based on that we are returning value.

 

Following is the result of above swift ternary operator example returned by playground.

 

y is greater than x

This is how we can use ternary operator in swift programming language based on our requirements. 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User