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.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on September 8, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui swift October 30, 2023 How to convert Color type to hex and vice-versa while retaining alpha information?

The below should work both on macOS and iOS with one minor change. That is, use UIColor instead of NSColor if you’re planning to use it for iOS.

question swiftui iOS April 2, 2024 How to force an app or a view to open in landscape only mode in iOS using SwiftUI?

In SwiftUI, you can force an app to open in landscape mode by configuring the supported interface orientations in your app’s target settings. Here’s a step-by-step guide to configuring interface orientations in Xcode:

question swiftui swift September 8, 2024 How to make Squircle shape in SwiftUI and how to easily convert it to a circle or a rectangle?

To create a squircle shape (a combination of a square and a circle, also known as a superellipse) in SwiftUI, you can define a custom shape by conforming to the Shape protocol and implementing the superellipse formula. The formula for a superellipse is: