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.
var marks = 80
num1 == num2
These expressions, for instance, assign the value 80 to the variable marks
, and compare the values of num1
and num2
, respectively.
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.
print("Hello World")
The humble print
statement, for example, 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
- Conditional Statements: Making Decisions in Your Code
- Loop Statements: Repeating Tasks with Ease
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.
var score = 9 * 5
print("Hello World")
For example, the statement 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.
if (age > 18) {
// code to be executed
}
For instance, the statement 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.
for i in 1...3 {
print("Hello World")
}
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.
{
let sum = 2+3
print("Result is \(sum)")
}
For example, the code block consists of two statements: one that calculates the sum
and another that prints the result.