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.
Following is the swift ternary operator flow diagram to represent how the functionality of ternary operator will work in swift programming language.
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.
Following is the syntax of ternary operator in swift programming language.
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.
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")
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.
This is how we can use ternary operator in swift programming language based on our requirements.