Loading...

How to loop through an enum in SwiftUI?

question swiftui swift
Ram Patra Published on September 8, 2024

In SwiftUI, looping through an enum is not directly possible without some extra work because enums in Swift don’t inherently support iteration. However, you can achieve this by making the enum CaseIterable, which automatically provides a collection of all cases in the enum.

Here’s how you can loop through an enum using CaseIterable:

Example

import SwiftUI

// Define your enum and make it conform to CaseIterable
enum Fruit: String, CaseIterable {
    case apple = "Apple"
    case banana = "Banana"
    case cherry = "Cherry"
}

struct ContentView: View {
    var body: some View {
        // Use List to loop over the enum cases
        List(Fruit.allCases, id: \.self) { fruit in
            Text(fruit.rawValue)
        }

        // Or, use ForEach to loop over the enum cases
        ForEach(Fruit.allCases) { fruit in
            Text(fruit.rawValue)
                .padding()
                .font(.title2)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Explanation

  • CaseIterable automatically synthesizes a static allCases property, which is an array containing all the cases of the enum.
  • You can loop through Fruit.allCases in a SwiftUI List or any other loop construct.
  • id: \.self ensures each fruit case is uniquely identifiable, which is necessary when using enums in views like List.

This is the easiest way to loop through an enum in SwiftUI.

Take your presentation to the next level.

Put your face and name on your screen.

Your to-dos on your menu bar.

Fill forms using your right-click menu.

Ram Patra Published on September 8, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui March 6, 2023 How to render the icon on a menu bar as a template in SwiftUI?

Setting your app’s icon on the menu bar as a template makes it to adapt to light and dark modes automatically without you doing anything. To do this, you have to use this constructor of MenuBarExtra class.

question swiftui macOS January 26, 2024 How to hide the title bar in a SwiftUI macOS app?

Let’s say you have a view named ContentView and your main App file looks like this:

question swiftui macos October 15, 2023 How to display the app version and build number in a macOS/iOS SwiftUI app?

To display both the app version and build number in a SwiftUI macOS/iOS app, you can use the Bundle class to access information from the app’s Info.plist file. The Info.plist file contains various details about your application, including its version and build number. Here’s how you can do it:

Like my work?

Please, feel free to reach out. I would be more than happy to chat.