Swift Statements

Swift Statements

A computer program is essentially a list of instructions that the computer executes.

In Swift, each of these individual instructions is called a statement.

Swift executes statements sequentially, one after the other, from the top of the file to the bottom.

Understanding how to construct statements is key to building logical programs.


What is a Statement?

A statement can be an assignment, a function call, or a control flow execution.

When you tell Swift to print a string, you are writing a statement.

When you define a new variable and give it a value, you are also writing a statement.

Examples of Statements:

let x = 10        // Statement 1
let y = 20        // Statement 2
let sum = x + y   // Statement 3
print(sum)        // Statement 4

Multiple Statements on One Line

Normally, you write one statement per line to keep your code clean and readable.

However, Swift allows you to write multiple statements on the same line.

To do this, you must separate each statement with a semicolon ;.

Inline Statements:

let a = 5; let b = 15; print(a + b)

While this is valid Swift syntax, it is generally discouraged because it makes the code harder to read.


Control Flow Statements

Statements aren't just for doing math or printing text.

Control flow statements tell the program to make decisions or repeat actions.

Examples of control flow statements include if, switch, for, and while.

We will cover these specific types of statements in much greater detail in later chapters.


Expressions vs Statements

It's important to understand the difference between an expression and a statement.

An expression evaluates to a value (e.g., 5 + 5 evaluates to 10).

A statement performs an action but does not necessarily return a value (e.g., print("Hello")).


Exercise

How do you separate multiple statements on a single line in Swift?