Swift programming for Beginners – Swift Operator precedence and associativity

(Swift for Beginners)

Swift Operator precedence and associativity

In this article you will learn about the rules used to evaluate a expression with operators and operands.

Swift Operator precedence

Operator precedence is a collection of rules used in order to evaluate a given mathematical expression. When there are several operators used in a single expression, each part is evaluated in a certain order called as operator precedence. Certain operators have higher priority than others which affects how an expression is evaluated.


Operator precedence table

The table below lists the precedence of operators in Swift. Higher it appears in the table, the higher its precedence.

Swift Standard Library Precedence Groups (Highest to Lowest)
Operator Groups Examples
Bitwise shift precedence >> &<< &>> >>
Multiplication precedence &* % & * /
Addition precedence | &+ &- + –  ^
Range Formation Precedence ..< …
Casting Precedence is as
Nil-Coalescing Precedence ??
Comparison Precedence != > < >= <= === ==
Logical Conjunction Precedence &&
Logical Disjunction Precedence ||
Default Precedence ~>
Ternary Precedence ?:
Function Arrow precedence ( )
Assignment Precedence |= %= /= &<<= &>>= &= *= >>= <<= ^= += -=

Example 1: Swift Operator Precedence

let x = 4 + 5 * 5
print(x)

When you run the above program, the output will be:

29

In the above example, if you read the expression from left to right, you might expect the output to be 45. But, multiplication operator has a higher precedence than addition operator so the expression 4 + 5 * 5 is evaluated as 4 + (5 * 5) . Therefore print(x) outputs 29 in the screen.

Execution Steps
Steps Operator Expression Value returned from expression
1 * 5 * 5 25
2 + 4 + 25 29
3 = print(x) 29

Example 2: Swift Operator Precedence with complex assignment operator

var y = 15
y += 10 - 2 * 3
print(y)

When you run the above program, the output will be:

19

In the above example, the expression var y = 15 assigns value 15 in the variable y.

In the next expression y += 10 - 2 * 3 the multiplication operator has a higher precedence than subtraction & compound assignment operator(+=).

Therefore, the expression y += 10 - 2 * 3 is evaluated as y = y + (10 - (2 * 3)).

Execution Steps
Steps Operator Expression Value returned from expression
1 = var y = 15 15
2 * 2 * 3 6
3 10 – 6 4
4 += 15 + 4 19

Swift Operator Associativity

Although there are predefined rules defined by operator precedence to evaluate an expression, you might be wondering what happens if there are multiple operators of the same precedence level. The operator associativity defines how operators of the same precedence are grouped together.

In Swift, operators can be either left-associative, right-associative or have no associativity. Operators that are left-associative, group their operands from the left of the statement, right-associative operators from the right and operators with no associativity have no defined behaviour when used in sequence in an expression.


Operator associativity table

The table below shows the associativity of Swift operators along with the precedence.

Swift Standard Library Associativity (Precedence Highest to Lowest)
Operator Groups Examples Associativity
Bitwise shift precedence >> &<< &>> >> none
Multiplication precedence &* % & * / left
Addition precedence | &+ &- + –  ^ left
Range Formation Precedence ..< … none
Casting Precedence is as none
Nil-Coalescing Precedence ?? right
Comparison Precedence != > < >= <= === == none
Logical Conjunction Precedence && left
Logical Disjunction Precedence || left
Default Precedence ~> none
Ternary Precedence ?: right
Function Arrow precedence ( ) right
Assignment Precedence |= %= /= &<<= &>>= &= *= >>= <<= ^= right

Example 3: Swift Operator Associativity

let x =  40  / 2 * 10
print(x)

When you run the above program, the output will be:

200

In the above program, the expression is evaluated from left to right because the operators fall into multiplication precedence groups and has left associativity. Therefore, the division operation takes place earlier and you get the result 200. What if you want to execute the multiplication first? You need to wrap the 2 * 10 expression into () braces as:

let x =  40  / (2 * 10)
print(x)

When you run the above program, the output will be:

2

You don’t need to memorize the precedence and associative table. Most of the time, the precedence and associativity of operators makes sense in itself. You can always use the table for reference when in doubt. Also, it’s better to use parenthesis to make your code easier to understand.

 

Swift programming for Beginners – Swift Operator precedence and associativity

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!