Unlocking the Power of Swift: Expressions, Statements, and Code Blocks
The Building Blocks of Swift: Expressions
In Swift, an expression is a combination of variables, operators, literals, and functions that evaluates to a single value. Think of it as a recipe that yields a specific result. For instance, var marks = 80
assigns the value 80 to the variable marks
, while num1 == num2
compares the values of num1
and num2
.
Statements: The Instructions That Drive Your Code
Statements are the backbone of your Swift code, providing specific instructions for the computer to execute. They can be as simple as printing a message to the screen or as complex as controlling the flow of your program. Take, for example, the humble print
statement, which displays the text “Hello World” to the user.
The Three Types of Statements in Swift
Swift statements come in three flavors:
Simple Statements: Assigning Values and Declaring Variables
Simple statements are the most common type of statement in Swift. They consist of either an expression or a declaration. For example, var score = 9 * 5
assigns the result of the expression 9 * 5
to the variable score
. The print
statement is also a simple statement.
Conditional Statements: Making Decisions in Your Code
Conditional statements allow you to execute a block of code only when certain conditions are met. For instance, if (age > 18)
checks whether the age
variable is greater than 18, and if true, executes the code within the block. There are two types of conditional statements in Swift: if...else
and switch
.
Loop Statements: Repeating Tasks with Ease
Loop statements enable you to repeatedly execute a block of code. Take, for example, the for
loop statement for i in 1...3
, which executes the print
statement three times. Swift offers three types of loop statements: for-in
, while
, and repeat while
.
Code Blocks: Grouping Statements Together
A code block is a group of statements (zero or more) enclosed in curly braces { }
. It’s a way to organize your code into logical sections. For example, the code block let sum = 2+3; print("Result is \(sum)")
consists of two statements: one that calculates the sum and another that prints the result.