Swift: Controlling Order of Execution

Controlling Order of Execution in Swift:

Let’s discuss about controlling order of execution in Swift.

Because we can set operator precedence ourselves instead of relying on the compiler by wrapping a logical expression in parentheses (). So, it makes our code easier to read and understand.

Consider the logical expression below, which contains multiple logical operators:

false && true && true || true

The execution order may appear ambiguous at first, but by following Swift’s operator precedence rules, we can achieve the Boolean result false:

Step 1: false && true && true || true
Step 2: false && true || true 
Step 3: false || true
Result: true

If we wanted more control over the evaluation of this expression, we can use parentheses to direct the order of execution and improve the expression’s readability:

(false && true) && (true || true)

Step 1: (false && true) && (true || true)
Step 2: false && (true || true) 
Step 3: false && true 
Result: false

Observe how, despite using the same operators, the expressions give different results. So, Swift’s operator precedence rules are overridden, and the order of operations is dictated by the presence of parentheses.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: