in , ,

Swift Expressions, Statements and Code blocks

Swift Expressions, Statements and Code blocks
Swift Expressions, Statements and Code blocks

Swift Expressions Statements blocks: In this tutorial, you will learn about Swift expressions, statements and blocks.

Swift Expressions

An expression is a combination of variables, operators, literals, and functions. For instance,

// assign value to marks
var marks = 80

// compare num1 and num2
var result = (num1 == num2)

Here, expressions are:

  • var marks = 80 – addresses we are assigning 80 to marks
  • num1 == num2 – thinks about num1 and num2

Swift Statements

Statements are guidelines to play out a particular task. For instance,

print("Hello World")

Here, we have used the print statement to teach the computer to show the content “Hello World”.

There are three sorts of statements in Swift:

1. Simple Statements

The straightforward statements comprises of either an expression or declaration. For instance,

var score = 9 * 5

Here, var score = 9 * 5 is a statement that assigns out the result of 9 * 5 to the score variable.

Simple statements are the most well-known sorts of statements in Swift. The print statement we have used before is likewise an illustration of simple statements.

2. Conditional Statements

The conditional statement allows us to execute a specific block of code just when certain conditions are met. For instance,

var age = 25

if (age > 18) {
  print("Can Vote")

In the above example, if (age > 18) is a conditional statement. Here, the print statement is possibly executed if the condition age > 18 is true.

3. Loop Statements

Loop statements allow us to more than once execute a block of code. For instance,

// create a loop statement
for i in 1...3 {
    print("Hello, World!")


Hello, World!
Hello, World!
Hello, World!

In the above example, we have used a for loop statement: for I in 1…3. It executes the print statement 3 times.

Swift Code Blocks

A code block is a group of statements (zero or more) that is enclosed in curly braces { }. For instance,

if true { // start of block
let sum = 2+3
print("Result is \(sum)")

} // end of block

Here, the code block consists two statements:

let sum = 2+3
print(“Result is (sum)”)

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

HTML Comments

HTML Comments

HTML Colors

HTML Colors