Operator Precedence in Swift šŸŽÆ

beginner
13 min

Operator Precedence in Swift šŸŽÆ

Welcome back, coding enthusiast! Today, we're diving into the fascinating world of Operator Precedence in Swift. Let's get started!

What is Operator Precedence? šŸ“

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.

Basic Operators in Swift šŸ’”

Swift has a variety of operators, but for this lesson, we'll focus on the basic arithmetic and comparison operators:

  1. Arithmetic Operators: +, -, *, /, % (modulo)
  2. Comparison Operators: ==, !=, <, >, <=, >=

Operator Precedence Rules šŸ’”

  1. Swift follows a predefined order to evaluate expressions. Operators higher in the list are evaluated before the ones lower in the list.

  2. Parentheses () can be used to change the order of evaluation.

  3. When multiple operators of the same precedence are present, they are evaluated from left to right.

Example 1: Basic Arithmetic āœ…

swift
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.

Example 2: Comparison Operators āœ…

swift
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.

Operator Precedence Quiz šŸ’”

Quick Quiz
Question 1 of 1

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! šŸ¤–