Get 50% off during WWDC 2025!

Design+Code logo

Quick links

Suggested search

1. Introduction to Loops in Swift

Loops are fundamental programming constructs that allow you to execute a block of code repeatedly. Instead of writing the same code multiple times, loops help you automate repetitive tasks, making your code more concise and maintainable.

A. Why Loops Matter

i. Efficiency: Loops eliminate the need to write repetitive code, reducing the chances of errors and making your codebase more manageable.

ii. Data processing: Loops are essential for processing collections of data, such as arrays, dictionaries, or any sequence of elements.

iii. Dynamic operations: Loops enable your app to perform operations whose repetition count is determined at runtime.

B. Types of Loops in Swift

Swift offers several types of loops, each designed for specific scenarios:

i. For-in loops: Ideal for iterating through a sequence (like an array, range, or string).

ii. While loops: Used when you need to repeat code until a condition becomes false.

iii. Repeat-while loops: Similar to while loops but guarantees at least one execution of the code block.

In this guide, we'll focus on for-in loops (commonly called for-loops) and how they work with ranges.

2. For-Loops Basics

The for-loop is the most commonly used loop in Swift, especially when working with collections or when you know exactly how many times you need to repeat an operation.

A. Syntax and Structure

The basic syntax of a for-loop in Swift is:

for item in collection {
    // Code to execute for each item
}

Where:

  • item is a constant that represents the current element in each iteration
  • collection is what you're iterating through (array, range, or any other sequence)

B. Iterating Through Ranges

One of the most common uses of for-loops is to iterate through a range of numbers:

for number in 1...5 {
    print(number)
}
// Prints: 1, 2, 3, 4, 5

C. Common Use Cases

i. Processing array elements:

let fruits = ["Apple", "Banana", "Orange"]
for fruit in fruits {
    print("I like \(fruit)s")
}

ii. Repeating an action a specific number of times:

for _ in 1...3 {
    print("Hello!")
}
// Prints "Hello!" three times

iii. Iterating with index and value using enumerated():

let colors = ["Red", "Green", "Blue"]
for (index, color) in colors.enumerated() {
    print("\(index): \(color)")
}
// Prints: 0: Red, 1: Green, 2: Blue

3. Understanding Ranges

Ranges in Swift are a powerful way to represent a sequence of values. They're particularly useful with for-loops for iterating through a series of numbers.

A. Closed Range Operator (...)

The closed range operator creates a range that includes both the lower and upper bounds:

for num in 1...5 {
    print(num)
}
// Prints: 1, 2, 3, 4, 5

B. Half-Open Range Operator (..<)

The half-open range operator includes the lower bound but excludes the upper bound:

for num in 1..<5 {
    print(num)
}
// Prints: 1, 2, 3, 4

This is particularly useful when working with arrays, as their indices start at 0 and go up to (but not including) the count:

let array = ["A", "B", "C", "D"]
for i in 0..<array.count {
    print("Index \(i): \(array[i])")
}

C. One-Sided Ranges

Swift also supports one-sided ranges, where you specify only one bound:

i. Lower bound only:

let numbers = [10, 20, 30, 40, 50]
for num in numbers[2...] {
    print(num)
}
// Prints: 30, 40, 50

ii. Upper bound only:

let numbers = [10, 20, 30, 40, 50]
for num in numbers[..<3] {
    print(num)
}
// Prints: 10, 20, 30

D. Stride Function

When you need to iterate with specific steps (not just by 1), use the stride function:

// Count from 0 to 10 by 2s
for num in stride(from: 0, to: 11, by: 2) {
    print(num)
}
// Prints: 0, 2, 4, 6, 8, 10

// Count from 10 down to 1
for num in stride(from: 10, to: 0, by: -1) {
    print(num)
}
// Prints: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

Note: stride(from:to:by:) excludes the upper bound, while stride(from:through:by:) includes it.

4. Practical Examples

Let's explore some common use cases for for-loops and ranges in real Swift applications.

A. Looping Through Arrays

Arrays are one of the most common data structures you'll work with:

let taskList = ["Buy groceries", "Clean house", "Pay bills", "Call mom"]

for task in taskList {
    print("ToDo: \(task)")
}

// With indices
for (index, task) in taskList.enumerated() {
    print("Task \(index + 1): \(task)")
}

B. Creating Patterns with Nested Loops

Nested loops (loops inside loops) are useful for working with multi-dimensional data or creating patterns:

// Printing a simple triangle pattern
for row in 1...5 {
    var line = ""
    for _ in 1...row {
        line += "* "
    }
    print(line)
}
/*
Prints:
* 
* * 
* * * 
* * * * 
* * * * * 
*/

C. Working with Indices

Sometimes you need direct access to array indices:

let scores = [85, 92, 78, 96, 88]
var totalScore = 0

// Calculate average score
for i in 0..<scores.count {
    totalScore += scores[i]
}

let averageScore = Double(totalScore) / Double(scores.count)
print("Average score: \(averageScore)")

5. Best Practices

A. When to Use For-Loops vs Other Loops

i. Use for-loops when:

  • You know exactly how many iterations you need
  • You're working with collections (arrays, dictionaries, strings)
  • You need to iterate through a specific range of numbers

ii. Use while/repeat-while loops when:

  • The number of iterations is not known in advance
  • The loop condition depends on external factors (like user input)
  • You need to check the condition before or after each iteration

B. Performance Considerations

i. Avoid modifying the collection you're iterating through:

// Avoid this pattern:
var numbers = [1, 2, 3, 4, 5]
for number in numbers {
    if number % 2 == 0 {
        numbers.remove(at: numbers.firstIndex(of: number)!)
    }
}

Instead, create a new collection or use specialized methods like filter().

ii. Use break to exit a loop early when possible:

for number in 1...1000 {
    if number * number > 10000 {
        print("First number with square > 10000: \(number)")
        break
    }
}

iii. Use continue to skip the current iteration:

for number in 1...10 {
    if number % 2 == 0 {
        continue // Skip even numbers
    }
    print(number) // Prints only odd numbers
}

C. Common Mistakes to Avoid

i. Off-by-one errors: Be careful with the difference between closed ranges (...) and half-open ranges (..<).

ii. Infinite loops: While this is more common with while loops, be careful not to create a situation where your loop never terminates.

iii. Unnecessary iteration: Sometimes functions like map, filter, or reduce can be more efficient and readable than manual for-loops.

6. SwiftUI Specific Applications

In SwiftUI, for-loops are often used with the ForEach view to create dynamic lists of views:

struct ContentView: View {
    let colors = ["Red", "Green", "Blue", "Yellow", "Purple"]

    var body: some View {
        List {
            ForEach(0..<colors.count, id: \.self) { index in
                Text("\(index + 1). \(colors[index])")
            }
        }
    }
}

This creates a dynamic list where each row is a numbered color name.

7. Summary

For-loops and ranges are fundamental tools in Swift programming that allow you to:

  • Iterate through collections efficiently
  • Repeat code a specific number of times
  • Process data in a sequential manner
  • Create dynamic user interfaces in SwiftUI

Understanding how to use the different range operators (..., ..<) and special functions like stride() and enumerated() will help you write more efficient and readable code as you continue your Swift journey.

Remember that for-loops are just one tool in your programming arsenal. As you advance, you'll discover functional programming alternatives like map(), filter(), and reduce() that can sometimes replace loops with more concise code.

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

Swift Dictionaries

READ NEXT

Optionals

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

Videos

Assets

1

Building Your iOS Development Foundation

Master the fundamentals of Swift programming with hands-on examples designed for beginners and experienced developers alike

2

SwiftUI Print Debugging

Print debugging: Unlock the invisible processes with strategic print statements that illuminate state changes, view lifecycles and data flow

18:04

3

Comments Documentation Waypoints

Transform your code from mysterious instructions to a comprehensive narrative with strategic comments that explain the why

22:02

4

Variables and Constants

Learn when and how to use variables and constants to write safer, more efficient SwiftUI code

11:37

5

Strings and Interpolation

Learn essential string operations in Swift: Build better iOS apps with efficient text handling techniques

13:22

6

Swift Operators: The Foundation of SwiftUI Logic

Building powerful iOS apps through the language of operations

5:34

7

Swift Unary Operators

Mastering the elegant simplicity of unary operators for cleaner, more expressive SwiftUI code that transforms your UI with minimal syntax

15:00

8

Swift Binary Operators

Master the two-operand symbols that transform complex interface logic into concise, readable declarations

3:36

9

Arithmetic Operators

Learn how to implement and optimize arithmetic operations in SwiftUI, from basic calculations to complex mathematical interfaces

6:11

10

If-Else and Comparison Operators

Building Dynamic SwiftUI: Mastering If-Else and Comparison Operators

12:32

11

Logical Operators

Master SwiftUI's logical operators: Building intelligent iOS apps with robust decision-making systems

6:03

12

Ternary Operators

Use the power of Swift's ternary conditional operator to create dynamic, responsive interfaces with minimal code in SwiftUI

6:22

13

Blocks and Scope

A comprehensive guide to writing clean, organized code through proper variable management and state control

10:22

14

Swift Collections: Arrays, Sets, and Dictionaries Overview

Organize Your Data Effectively: Learn How to Choose and Optimize the Perfect Collection Type for Your SwiftUI Applications

7:00

15

Swift Arrays

Organize, transform, and display your data with Swift's most essential collection structure

8:54

16

Swift Sets

Mastering Unique Collections with Fast Lookups and Powerful Operations

11:03

17

Swift Dictionaries

Master Swift's key-value collection type with practical examples for efficient data storage, retrieval, and transformation in SwiftUI apps

18

For-Loops and Range

For-Loops and Ranges: Learn how to repeat code efficiently and work with sequences of numbers in Swift

19

Optionals

Optionals in Swift: Understanding Swift's Safety System for Handling Missing Values

20

Functions

Functions in Swift: Building Reusable Code Blocks to Organize and Streamline Your App

Meet the instructor

We all try to be consistent with our way of teaching step-by-step, providing source files and prioritizing design in our courses.

Sourasith Phomhome

UI Designer

Designer at Design+Code

icon

20 courses - 78 hours

course logo

Master Agentic Workflows

In this course, you’ll learn how to add agents to your workflows. An agent workflow is more than just a simple automation. Instead of following a fixed script, agents can make decisions, adjust to changes, and figure out the best way to complete a task. We’ll start by exploring what MCP servers are and all the new possibilities they bring. Then, we’ll dive into agentic frameworks that make it easy to build flexible, helpful agents that can take care of your everyday tasks.

2 hrs

course logo

Design Multiple Apps with Figma and AI

In this course, you’ll learn to design multiple apps using Figma and AI-powered tools, tackling a variety of real-world UI challenges. Each week, a new episode will guide you through a different design, helping you master essential UI/UX principles and workflows

4 hrs

course logo

SwiftUI Fundamentals Handbook

A comprehensive guide to mastering Swift programming fundamentals, designed for aspiring iOS developers. This handbook provides a structured approach to learning Swift's core concepts, from basic syntax to advanced programming patterns. Through carefully sequenced chapters, readers will progress from essential programming concepts to object-oriented principles, building a solid foundation for SwiftUI development. Each topic includes practical examples and clear explanations, ensuring a thorough understanding of Swift's capabilities. This handbook serves as both a learning resource and a reference guide, covering fundamental concepts required for modern iOS development. Topics are presented in a logical progression, allowing readers to build their knowledge systematically while gaining practical programming skills.

2 hrs

course logo

Design and Code User Interfaces with Galileo and Claude AI

In this course, you’ll learn how to use AI tools to make UI/UX design faster and more efficient. We’ll start with Galileo AI to create basic designs, providing a solid foundation for your ideas. Next, we’ll refine these designs in Figma to match your personal style, and finally, we’ll use Claude AI to turn them into working code—eliminating the need for traditional prototyping.

4 hrs

course logo

Build a React Native app with Claude AI

This comprehensive course explores the integration of cutting-edge AI tools into the React Native development workflow, revolutionizing the approach to mobile application creation. Participants will learn to leverage AI-powered platforms such as Claude and Locofy to expedite coding processes, enhance problem-solving capabilities, and optimize productivity.

14 hrs

course logo

Design and Prototype for iOS 18

Design and Prototype for iOS 18 is an immersive course that equips you with the skills to create stunning, user-friendly mobile applications. From mastering Figma to understanding iOS 18's latest design principles, you'll learn to craft two real-world apps - a Car Control interface and an AI assistant.

3 hrs

course logo

Master Responsive Layouts in Figma

Creating responsive layouts is a must-have skill for any UI/UX designer. With so many different devices and screen sizes, designing interfaces that look great and work well on all platforms is necessary. Mastering this skill will make you stand out in the field. In this course, we'll start from scratch to create this beautiful design using Figma. You'll learn how to make layouts that are easy to use and work well on any device. We'll cover key concepts and tools to help you master responsive design in Figma.

2 hrs

course logo

UI UX Design with Mobbin and Figma

Mobbin is a powerful tool for UI/UX designers seeking inspiration and innovative design solutions. This platform offers a vast collection of real-world mobile app designs, providing a treasure trove of UI elements and layouts.

2 hrs

course logo

3D UI Interactive Web Design with Spline

Learn to create 3D designs and UI interactions such as 3D icons, UI animations, components, variables, screen resize, scrolling interactions, as well as exporting, optimizing, and publishing your 3D assets on websites

3 hrs

course logo

Design and Prototype for iOS 17 in Figma

Crafting engaging experiences for iOS 17 and visionOS using the Figma design tool. Learn about Figma's new prototyping features, Dev Mode, variables and auto layout.

6 hrs

course logo

Design and Prototype Apps with Midjourney

A comprehensive course on transforming Midjourney concepts into interactive prototypes using essential design techniques and AI tools

8 hrs

course logo

iOS Design with Midjourney and Figma

Learn the fundamentals of App UI design and master the art of creating beautiful and intuitive user interfaces for mobile applications

1 hrs

course logo

UI Design for iOS, Android and Web in Sketch

Create a UI design from scratch using Smart Layout, Components, Prototyping in Sketch app

1 hrs

course logo

UI Design a Camera App in Figma

Design a dark, vibrant and curvy app design from scratch in Figma. Design glass icons, lens strokes and realistic buttons.

1 hrs

course logo

UI Design for iOS 16 in Sketch

A complete guide to designing for iOS 16 with videos, examples and design files

3 hrs

course logo

Prototyping in Figma

Learn the basics of prototyping in Figma by creating interactive flows from custom designs

1 hrs

course logo

UI Design Quick Websites in Figma

Learn how to design a portfolio web UI from scratch in Figma

1 hrs

course logo

UI Design Android Apps in Figma

Design Android application UIs from scratch using various tricks and techniques in Figma

2 hrs

course logo

UI Design Quick Apps in Figma

Design application UIs from scratch using various tricks and techniques in Figma

12 hrs

course logo

Figma Handbook

A comprehensive guide to the best tips and tricks in Figma

6 hrs