Swift Operator Precedence
🔢 Swift Operator Precedence (Clear & Easy Guide)
👉 Just like mathematics:
BODMAS → () → * / % → + -
Why Operator Precedence Matters
Wrong understanding = wrong result ❌
Output:
✔ * has higher precedence than +
Basic Precedence Order (High → Low)
| Priority | Operator Type | Examples |
|---|---|---|
| 1️⃣ | Parentheses | ( ) |
| 2️⃣ | Unary | !, -a |
| 3️⃣ | Multiplicative | * / % |
| 4️⃣ | Additive | + - |
| 5️⃣ | Range | ... ..< |
| 6️⃣ | Comparison | == != > < >= <= |
| 7️⃣ | Logical AND | && |
| 8️⃣ | Logical OR | ` |
| 9️⃣ | Ternary | ? : |
| 🔟 | Assignment | = += -= |
Arithmetic Operator Precedence
Output:
✔ Multiplication first
Using Parentheses (Best Practice ✅)
Output:
✔ Parentheses override precedence
Logical Operator Precedence
Output:
✔ && evaluated before ||
Comparison + Logical Operators
✔ Comparison before logical AND
Ternary Operator Precedence
Lower than comparison, higher than assignment.
Nil-Coalescing Operator (??) Precedence
Higher than comparison, lower than arithmetic.
❌ Common Mistakes
❌ Assuming left-to-right always:
❌ Complex expressions without parentheses:
✅ Better:
🧠 Quick Memory Trick 🧩
🎯 Summary
-
Operator precedence controls evaluation order
-
Parentheses
()override all rules -
* / %before+ - -
&&before|| -
Use parentheses for clarity
