struct QuizView: View {
// The question pool.
var questions = [("What is the capital of France?", ["Paris", "London", "New York", "San Francisco"], "Paris"),
("What is the capital of Italy?", ["Rome", "Paris", "Madrid", "Berlin"], "Rome"),
("What is the capital of Spain?", ["Barcelona", "Madrid", "Rome", "Paris"], "Madrid"),
("What is the capital of Germany?", ["Berlin", "Paris", "London", "New York"], "Berlin"),
("What is the capital of the UK?", ["London", "Paris", "Madrid", "New York"], "London"),
]
// The current question.
@State var currentQuestion = 0
// The user's score.
@State var score1 = 0
// The indices of the remaining questions.
@State var remainingQuestions = [Int]()
var body: some View {
VStack {
currentView
}.onAppear {
questions.shuffle() // shuffle the questions array
remainingQuestions = Array(0..<questions.count) // recreate remainingQuestions array
}
}
}
错误信息:
不能在不可变值上使用可变成员:'self'是不可变的
我实际上想让代码使问题将洗牌,但显然这发生了,我也是新的。
下面是一个简单的例子:
struct QuizView: View {
// The question pool.
@State var questions = [
("Q1", "A1"),
("Q2", "A2"),
("Q3", "A3"),
]
// The current question.
@State var currentQuestion: (String, String) = ("", "")
var body: some View {
VStack {
currentView
}.onAppear(perform: nextQuestion)
}
// Grab the next question, removing it from the question pool.
func nextQuestion() {
questions.shuffle()
currentQuestion = questions.remove(at: 0)
}
}
由于使用了@State
,您可以期望currentView
在调用nextQuestion()
时更新currentQuestion
的显示。