0
0
iOS Swiftmobile~20 mins

List with ForEach in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Fruits List
This screen shows a list of fruit names using a ForEach loop inside a SwiftUI List.
Target UI
-------------------
| Fruits List     |
-------------------
| * Apple         |
| * Banana        |
| * Cherry        |
| * Date          |
| * Elderberry    |
-------------------
Use a SwiftUI List to display fruit names.
Use ForEach to loop over an array of fruit strings.
Each fruit name should appear as a separate row in the list.
The screen should have a navigation title 'Fruits List'.
Starter Code
iOS Swift
import SwiftUI

struct FruitsListView: View {
    let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]

    var body: some View {
        NavigationView {
            // TODO: Add List with ForEach here
            Text("Replace this with the list")
                .navigationTitle("Fruits List")
        }
    }
}

struct FruitsListView_Previews: PreviewProvider {
    static var previews: some View {
        FruitsListView()
    }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
import SwiftUI

struct FruitsListView: View {
    let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]

    var body: some View {
        NavigationView {
            List {
                ForEach(fruits, id: \.self) { fruit in
                    Text(fruit)
                }
            }
            .navigationTitle("Fruits List")
        }
    }
}

struct FruitsListView_Previews: PreviewProvider {
    static var previews: some View {
        FruitsListView()
    }
}

We use a NavigationView to get a navigation bar with a title. Inside it, a List displays rows. The ForEach loops over the fruits array. We use id: \.self because the array contains unique strings. Each fruit name is shown in a Text view as a row. This creates a simple scrollable list of fruit names with a title.

Final Result
Completed Screen
-------------------
| Fruits List     |
-------------------
| * Apple         |
| * Banana        |
| * Cherry        |
| * Date          |
| * Elderberry    |
-------------------
User can scroll the list if it grows longer.
The navigation bar shows the title 'Fruits List'.
Stretch Goal
Add a button in the navigation bar that adds a new fruit to the list when tapped.
💡 Hint
Use @State to hold the fruits array and add a Button with a '+' icon in the navigation bar. Update the array inside the button's action.