9

Swift Ternary operator (?:)

 1 year ago
source link: https://sarunw.com/posts/swift-ternary-operator/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The Ternary operator is quite similar to if-else statements, but it isn't the same. Let's learn what it is and how to use it.

What is Swift Ternary operator

There are three types of operators in Swift.

  1. Unary operators which operate on a single target. For example, -1, !booleanValue, optionalValue!.
  2. Binary operators which operate on two targets. For eaxample, 2 + 3.
  3. Ternary operators which operate on three targets.

Since Swift has only one ternary operator, people usually refer Ternary operator to Ternary conditional operator (a ? b : c) (or ?:).

How to use Ternary Conditional Operator

The Ternary conditional operator is an operator with the following form.

condition ? expression1 : expression2

The ternary conditional operator checks the condition. Then evaluate and return the result from one of two expressions based on that condition.

  • If the condition is true, the first expression (expression1) is evaluated and returned.
  • If the condition is false, the second expression (expression2) is evaluated and returned.

You can say that it is a shorthand for the if-else statement.

if condition {
expression1
} else {
expression2
}

But there is a slight difference.

What is the difference between Ternary Conditional Operator and if-else

Even though we say that Ternary Conditional Operator is a shorthand for the if-else statement, there is one difference.

The ternary conditional operator is an operator. That means the result we get from the operator is a value.

The value is the result of evaluating either expression1 or expression2.

We can use this just like a normal value type.

Here is an example where we check whether the' number' is a negative or positive and return the result string.

let result: String
let number = 3

if number < 0 {
result = "Negative Number"
} else {
result = "Zero or Positive Number"
}

print(result)
// "Zero or Positive Number"

Here is the same code using Ternary Conditional Operator.

let number = 3
let result = number < 0 ? "Negative Number": "Zero or Positive Number"

print(result)
// "Zero or Positive Number"

As you can see, we can assign the result string to result directly, which is more concise in some cases.

Conclusion

The ternary conditional operator provides an efficient shorthand for deciding which of two expressions to consider.

But you should be mindful when using this. Overuse can lead to hard-to-read code.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK