0
0
iOS Swiftmobile~5 mins

List with ForEach in iOS Swift

Choose your learning style9 modes available
Introduction

We use List with ForEach to show a list of items on the screen. It helps us display many things easily by repeating a view for each item.

Showing a list of names in a contacts app.
Displaying a menu with many options.
Listing tasks in a to-do app.
Showing photos or messages in a feed.
Any time you want to show many similar items in a scrollable list.
Syntax
iOS Swift
List {
    ForEach(items, id: \.self) { item in
        Text(item)
    }
}

items is your data array.

id: \.self tells SwiftUI how to identify each item uniquely.

Examples
Shows a list of fruit names.
iOS Swift
let fruits = ["Apple", "Banana", "Cherry"]

List {
    ForEach(fruits, id: \.self) { fruit in
        Text(fruit)
    }
}
Shows a list of numbers with a label.
iOS Swift
let numbers = [1, 2, 3]

List {
    ForEach(numbers, id: \.self) { number in
        Text("Number: \(number)")
    }
}
Shows an empty list (no rows).
iOS Swift
let emptyList: [String] = []

List {
    ForEach(emptyList, id: \.self) { item in
        Text(item)
    }
}
Shows a list with only one item.
iOS Swift
let singleItem = ["Only one"]

List {
    ForEach(singleItem, id: \.self) { item in
        Text(item)
    }
}
Sample App

This app shows a list of animal names inside a navigation view with a title.

iOS Swift
import SwiftUI

struct ContentView: View {
    let animals = ["Dog", "Cat", "Rabbit"]

    var body: some View {
        NavigationView {
            List {
                ForEach(animals, id: \.self) { animal in
                    Text(animal)
                }
            }
            .navigationTitle("Animals")
        }
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
OutputSuccess
Important Notes

Time complexity: Displaying the list is O(n) where n is the number of items.

Space complexity: Depends on the number of items and views created.

Common mistake: Forgetting to provide a unique id for each item causes errors.

Use List with ForEach when you want a scrollable list that can handle dynamic data.

Summary

List with ForEach helps show many items easily.

Always provide a unique id for each item.

Works well for menus, contacts, tasks, and more.