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
CaseIterableautomatically synthesizes a staticallCasesproperty, which is an array containing all the cases of the enum.- You can loop through
Fruit.allCasesin a SwiftUIListor any other loop construct. id: \.selfensures eachfruitcase is uniquely identifiable, which is necessary when using enums in views likeList.
This is the easiest way to loop through an enum in SwiftUI.