我正在用 Swift 制作一个应用,用户必须回答一个问题。可以接受多个答案,因此我使用 ForEach 循环来检查所有答案。但是,当我尝试切换“正确”变量时(因此“正确!”消息仅显示一次),我收到错误(见标题)。错误显示在第 77 行:ForEach(0..<data.answer.count, id: .self)。有人知道如何修复这个问题吗???
import SwiftUI
struct LocationView: View {
@State private var submit: Bool = false
@State private var guess = ""
@State private var correct = false
var data: Location
var body: some View {
Text(data.question)
.padding()
TextField("Answer", text: $guess)
.padding()
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.green, lineWidth: 2)
)
.padding()
Button(action: {
submit.toggle()
}) {
Text("Submit")
.foregroundStyle(.blue)
.font(.headline)
}
if submit {
ForEach(0 ..< data.answer.count, id: \.self) { answer in
if guess == data.answer[answer] {
correct.toggle()
}
}
if correct {
Text("Correct!")
.foregroundStyle(.green)
.font(.headline)
}
}
}
}
}
#Preview {
let modelData = ModelData()
LocationView(data: modelData.locations[0])
}