Swift Operator Precedence

Swift Operator Precedence

Operator precedence determines evaluation order.

Multiplication comes before addition; && before ||.

Use parentheses to control order.


Control order of evaluation with precedence

Understand how operators are prioritized and add parentheses to make evaluation order explicit when needed.

Example

print(2 + 3 * 4)
print((2 + 3) * 4)
print(true || false && false)
print((true || false) && false)

This example shows how parentheses change the result.



Boolean Precedence

&& is evaluated before ||. Use parentheses to clarify intention.

Example

let a = true
let b = false
let c = true

print(a || b && c)         // true (&& before ||)
print((a || b) && c)       // true
print(a && b || c)         // true ((a && b) || c)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *