0

I want to show 2 sheets. One of them takes an argument. This code crashes when I try to show the second sheet, because the forcefully unwrapped argument was not assigned. This happens even though I assign it before I update the variable that triggers the showing of the sheet. How can someArgument still be nil?

This is all the code needed to reproduce the error:

enum ActiveSheet: Identifiable { case first, second var id: Int { hashValue } } struct ContentView: View { @State var activeSheet: ActiveSheet? @State var someArgument: String? var body: some View { VStack { Button { activeSheet = .first } label: { Text("Activate first sheet") } Button { someArgument = "Show this text" activeSheet = .second } label: { Text("Activate second sheet") } } .sheet(item: $activeSheet) { item in switch item { case .first: FirstView() case .second: SecondView(message: someArgument!) } } } } struct FirstView: View { var body: some View { Text("Hello I'm 1") } } struct SecondView: View { let message: String var body: some View { Text(message) } } 

I suppose that the reason this is not really straight forward is because NavigationLinks are usually used for this kind of use case.

1 Answer 1

2

One possible fix is to pass your argument string as an associated value of the ActiveSheet enum. That way, it will be available at the same time the enum is initialized:

enum ActiveSheet: Identifiable, Hashable { case first case second(String) var id: Int { hashValue } } struct ContentView: View { @State var activeSheet: ActiveSheet? var body: some View { VStack { Button { activeSheet = .first } label: { Text("Activate first sheet") } Button { activeSheet = .second("Show this text") } label: { Text("Activate second sheet") } } .sheet(item: $activeSheet) { item in switch item { case .first: FirstView() case .second(let someArgument): SecondView(message: someArgument) } } } } struct FirstView: View { var body: some View { Text("Hello I'm 1") } } struct SecondView: View { let message: String var body: some View { Text(message) } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.