SwiftUI: Use Enum to present Sheets
1 min read

SwiftUI: Use Enum to present Sheets

Hint: By the time of writing, this is the most recent way of how I would solve that issue. But as fast as Swift and SwiftUI is moving I can't guarantee that this valid when you are reading this post. 😉


If you ever need to show more than one Sheet on the same view in SwiftUI, you can easily end up in many isSheetXYPresented variables. But if the Sheets does not show any changeable data those booleans can be replaced with an nullable enum field like this:

import SwiftUI

enum ActionSheets: String {
    case foo
    case bar
}

extension ActionSheets: Identifiable {
    var id: String { rawValue }
}

struct FooView: View {
    var body: some View {
        Text("Foo")
    }
}

struct BarView: View {
    var body: some View {
        Text("Bar")
    }
}

struct ContentView: View {
    @State var selectedSheet: ActionSheets?
    
    var body: some View {
        VStack(spacing: 5) {
            Button("Foo") {
                selectedSheet = .foo
            }
            Button("Bar") {
                selectedSheet = .bar
            }
        }
        .sheet(item: $selectedSheet, content: { item in
            switch item {
            case .foo: FooView()
            case .bar: BarView()
            }
        })
    }
}

Which will look like this: