Welcome back, coding enthusiast! Today, we're diving into the fascinating world of Operator Precedence in Swift. Let's get started!
Operator precedence is a rule that defines the order in which operators are evaluated during the computation of an expression. In other words, it helps Swift to understand the order of operations when multiple operators are used in a single expression.
Swift has a variety of operators, but for this lesson, we'll focus on the basic arithmetic and comparison operators:
+, -, *, /, % (modulo)==, !=, <, >, <=, >=Swift follows a predefined order to evaluate expressions. Operators higher in the list are evaluated before the ones lower in the list.
Parentheses () can be used to change the order of evaluation.
When multiple operators of the same precedence are present, they are evaluated from left to right.
let a = 5
let b = 3
let result1 = a + b * 2
let result2 = (a + b) * 2
print("result1: \(result1)") // Output: result1: 13
print("result2: \(result2)") // Output: result2: 16š Note: In the above example, * has a higher precedence than +, so b * 2 is calculated first in result1. However, in result2, parentheses are used to change the order of evaluation, resulting in a different outcome.
let a = 5
let b = 3
let c = 2
if a > b && c < a {
print("a is greater than b and c is less than a")
}š Note: Here, we're using the > and < comparison operators. The condition a > b is evaluated first, then the c < a condition. If both conditions are true, the message is printed.
What will be the output of the following code?
That's it for today! Understanding operator precedence is crucial in writing clean, readable, and error-free code in Swift.
Keep coding, and happy learning! š¤