How come the sheet throws an Implicitly Unwrapped Optional
error when the button is pressed?
To me it looks like I'm assigning selectedNumber
to i
and then using it in the sheet, is there a step I'm missing where selectedNumber
is reset to nil?
import SwiftUI
struct ContentView: View {
@State private var selectedNumber: Int?
@State private var isShowingSheet = false
var body: some View {
ForEach(0..<10) { i in
Button("\(i)") {
selectedNumber = i
isShowingSheet = true
}
}
.sheet(isPresented: $isShowingSheet) {
Text("\(selectedNumber!)")
}
}
}
And when I move the sheet inside the loop to make the i
variable accessible it only shows 0
struct ContentView: View {
@State private var isShowingSheet = false
var body: some View {
ForEach(0..<10) { i in
Button("\(i)") {
isShowingSheet = true
}
.sheet(isPresented: $isShowingSheet) {
Text("\(i)")
}
}
}
}
The solution, as proposed by @BenzyNeez, was to use sheet(item:onDismiss:content:)
instead, with selectedNumber as the item.