Sitemap
Cong Le

Cong Le

iOS dev. Writing on Medium, I explore AI in mobile apps, including Stable Diffusion, LLMs, and beyond.𓂃🖊📱

Swift Basics — Loops

7 min readJan 21, 2024

--

a for loop is optimized to loop a set number of times

a while loop is optimized to loop an unknown number of times

a repeat while loop is always looped at least once

a switch statement is used to loop a finite number of specific cases

Loops

For Loop

In Swift, the for-in loop is used when you want to perform a set of instructions a certain number of times, or on a collection of items such as arrays, strings, and ranges.

Here’s the basic syntax of a for-in loop:

for item in collection {
// code to execute
}
  • item is the current item in the loop.
  • collection can be a sequence (like a range of numbers) or a collection (like an array).

Some examples of the for-in loop:

  1. Loop over a range of numbers:
for number in 1...5 {
print(number)
}

This will print numbers 1 through 5.

2. Loop over an array:

let fruits = ["apple", "banana", "orange"]
for fruit in fruits {
print(fruit)
}

This will print each fruit in the fruits array.

3. Loop over a string to access its characters:

for character in "Hello" {
print(character)
}

This will print each character in the string “Hello”.

4. Using enumerated() method to get index and value:

let fruits = ["apple", "banana", "orange"]
for (index, fruit) in fruits.enumerated() {
print("Item \(index+1): \(fruit)")
}

This will print the position and fruit in the fruits array.

Note: Swift also provides the stride() function for complex sequences.

stride()

The stride() function in Swift generates a sequence of numbers progressing from a starting value, increasing or decreasing by a specific amount (or 'stride'), and ending before a particular value.

Here is an example of stride() in Swift:

for i in stride(from: 0, to: 10, by: 2) {
print(i)
}

In this example, the numbers will start from 0 and end before 10, increasing by 2 each time. So it will print: 0, 2, 4, 6, 8.

Here’s another example with decreasing values:

for i in stride(from: 10, through: 0, by: -2) {
print(i)
}

We will get resulted sequence numbers as 10, 8, 6, 4, 2, 0

Applications of stride()

There are several practical uses for stride() in Swift. This function is especially useful because it allows you to specify a start point, an endpoint, and an increment (or decrement).

  1. Animations: You can use stride() to animate frames with specific intervals. For example, in a 60-frame-per-second animation, you could use stride() to animate every other frame (even frames) differently.
for frame in stride(from: 0, through: 60, by: 2) {
// render even frame animation
}

2. Audio/Visual Settings: Modify volume, brightness, or Position settings in small increments or decrements, like in my previous example.

3. Custom Animation Curves: When creating an animation curve, you might want to calculate the animation progress at fixed interval points. Here stride() can be used to correctly segregate the sequence at desired intervals.

for progress in stride(from: 0.0, to: 1.0, by: 0.1) {
let animationValue = calculateAnimationValue(at: progress)
// Render animation at this progress point
}

4. Games or Simulations: If you’re developing a game or a simulation, you might want to simulate movements from one coordinate to another coordinate in small incremental steps.

for xCoordinate in stride(from: 0.0, to: 100.0, by: 1.0) {
// simulate object movement from (xCoordinate, y) to the destination
}

5. Financial Calculations: When calculating compound interest over several periods, for example, stride() can iterate through each period.

for year in stride(from: 0, through: 10, by: 1) {
let balance = principal * pow(1 + rate, Double(year))
// process balance
}

These are just some examples that stride() can be useful. It's a handy method for generating sequences with specific characteristics.

While loop

In Swift, a while loop repeatedly executes a target statement as long as a given condition is true.

Get Cong Le’s stories in your inbox

Join Medium for free to get updates from this writer.

Here’s the basic syntax:

while condition {
statements
}

Here’s an example:

var counter = 0

while counter < 5 {
print("The counter is \(counter)")
counter += 1
}

In the above example:

  • The counter variable is initially set to 0.
  • The while loop checks if counter < 5.
  • If the condition is true, it enters the loop and executes the code block, printing the counter value and incrementing it by 1.
  • The while loop continues checking and processing the code block until counter is no longer less than 5.

So, this will print:

The counter is 0
The counter is 1
The counter is 2
The counter is 3
The counter is 4

Once counter reaches 5, the while loop stops because the condition counter < 5 becomes false.

Repeat While Loop

The repeat-while loop in Swift is a variation of the while loop. Each iteration of a repeat-while loop executes the block of code first, and then checks a condition. If the condition is true, the loop repeats, otherwise, it terminates and the program control moves on to the next statement after the repeat-while loop.

This means the code block in a repeat-while loop will always be executed at least once, no matter the condition, which differs from a while loop where the condition is checked before the code block is executed.

Here’s the syntax for a repeat-while loop in Swift:

repeat {
// code to execute
} while condition

Here’s a simple example:

var count = 0

repeat {
print("Hello, world!")
count += 1
} while count < 5

In this example, “Hello, world!” will be printed to the console five times. After each print, count is incremented by 1. When count is no longer less than 5, the loop terminates.

Switch Statement

In Swift, the switch statement is more powerful and flexible than in many other programming languages. It allows you to match multiple conditions and provides advanced pattern-matching capabilities.

Here is the basic syntax:

switch expression {
case value1:
// statements execute if expression matches value1
case value2:
// statements execute if expression matches value2
default:
// default statements execute if expression doesn't match any cases
}

Here’s a simple example:

let fruit = "Apple"

switch fruit {
case "Apple":
print("This is an apple")
case "Orange":
print("This is an orange")
default:
print("This is not an apple or an orange")
}

In this example, because the fruit variable is set to "Apple", the string "This is an apple" would be printed.

Note: Swift requires switch statements to be exhaustive. That means every possible value of the type you are switching on must be accounted for. That's why there is a default case in the switch block which will be executed if no match is found.

Swift switch statement also supports interval matching, tuple matching, compound cases, and so on, and does not require an explicit break statement like in C-based languages. Each case finishes executing once it hits the end of its code block.

Advancing with Switch Statement

Swift’s switch statement is very powerful, offering a lot more features compared to other programming languages. It provides more complex data handling and multiple pattern-matching functionalities.

Let’s get into a deeper dive of the switch statement:

1. Interval Matching — This allows you to check if a value lies within a certain range or interval. For instance, if you’re implementing a grading system for exams.

let examScore = 78

switch examScore {
case 90...100:
print("Grade is A")
case 80..<90:
print("Grade is B")
case 70..<80:
print("Grade is C")
case 60..<70:
print("Grade is D")
default:
print("Grade is F")
}

2. Tuple matching — You can also match tuples in a switch statement, which enables checking multiple values at once.

let somePoint = (1, 1)

switch somePoint {
case (0, 0):
print("\(somePoint) is at the origin")
case (_, 0):
print("\(somePoint) is on the x-axis")
case (0, _):
print("\(somePoint) is on the y-axis")
default:
print("\(somePoint) is not on an axis")
}

In the above example, (0, 0) matches the origin, (_, 0) matches any point on the x-axis, and (0, _) matches any point on the y-axis.

Suppose you’re working on a 2D game and need to identify directions based on x, and y coordinates.

let playerMovement = (0, -1)

switch playerMovement {
case (0, 1):
print("Player moves upward")
case (0, -1):
print("Player moves downward")
case (1, 0):
print("Player moves to the right")
case (-1, 0):
print("Player moves to the left")
default:
print("Player stands still")
}

3. Value Bindings — Swift’s switch statement lets you bind the matched value to a temporary constant or variable for use in the case's body.

let anotherPoint = (2, 0)

switch anotherPoint {
case (let x, 0):
print("On the x-axis with an x value of \(x)")
case (0, let y):
print("On the y-axis with a y value of \(y)")
case let (x, y):
print("Somewhere not on an axis at (\(x), \(y))")
}

Identify the quadrant of a point in a 2D space.

let point = (-3, -5)
switch point {
case let (x, y) where x > 0 && y > 0:
print("(\(x), \(y)) is in Quadrant I")
case let (x, y) where x < 0 && y > 0:
print("(\(x), \(y)) is in Quadrant II")
case let (x, y) where x < 0 && y < 0:
print("(\(x), \(y)) is in Quadrant III")
case let (x, y) where x > 0 && y < 0:
print("(\(x), \(y)) is in Quadrant IV")
case (_, _):
print("Point is on the axis")
}

4. Compound Cases — Multiple possible matches for the same case body can be written on a single line, separated by commas. You can also bind values and check for values within a certain range.

let stillAnotherPoint = (1, -1)

switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
print("On an axis, \(distance) from the origin")
default:
print("Not on an axis")
}

Imagine you’re building an app that should respond differently to various categories of products.

let productCategory = "Electronics"

switch productCategory {
case "Garden", "Tools":
print("Handling Garden and Tools category")
case "Electronics", "Computers":
print("Handling Electronics and Computers category")
case "Clothing", "Fashion":
print("Handling Clothing and Fashion category")
default:
print("Unhandled product category")
}

Using these features, you can write very detailed and expressive conditional logic with switch statements in Swift.

--

--

Cong Le
Cong Le

iOS dev. Writing on Medium, I explore AI in mobile apps, including Stable Diffusion, LLMs, and beyond.𓂃🖊📱