swift - Sheet `Implicitly Unwrapped Optional` - Stack Overflow

admin2025-05-01  0

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)")
            }
        }
    }
}

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)")
            }
        }
    }
}
Share Improve this question edited Jan 2 at 23:58 malhal 31k7 gold badges123 silver badges150 bronze badges asked Jan 2 at 21:36 The-WolfThe-Wolf 857 bronze badges 2
  • 1 You could consider using sheet(item:onDismiss:content:) instead, with selectedNumber as the item. – Benzy Neez Commented Jan 2 at 21:42
  • @BenzyNeez thank you, I wasn't aware this existed – The-Wolf Commented Jan 2 at 21:51
Add a comment  | 

1 Answer 1

Reset to default 0

The solution, as proposed by @BenzyNeez, was to use sheet(item:onDismiss:content:) instead, with selectedNumber as the item.

转载请注明原文地址:http://anycun.com/QandA/1746095703a91604.html