【问题标题】:SwiftUI error code, i do not know how to fix itSwiftUI错误代码,我不知道如何解决
【发布时间】:2023-01-12 18:17:09
【问题描述】:
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' 是不可变的

我实际上想编写代码,以便问题会随机播放,但显然这发生了,我也是新手。

【问题讨论】:

  • 那么错误是什么?你在哪里挣扎?
  • 究竟发生了什么,什么错误代码?
  • 嗨@Shlok,欢迎来到 Stack Overflow。请更新您的代码以显示重现该问题的最小示例;理想情况下,有人可以将其粘贴到 Xcode 中并运行的 struct ContentView。请看minimal reproducible example
  • 不能在不可变值上使用可变成员:'self' 是不可变的,这是错误
  • 在哪里?哪一行导致错误?这是一个编译错误,而不是运行时错误。

标签: swift swiftui


【解决方案1】:

如果你想在 SwiftUI 视图中操作一个 var,你需要将它包装到一个 @State 属性包装器中。例如。:

@State 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"),
    ]

【讨论】:

  • 我做到了,错误消失了,但我无法改变测验的问题。
  • @ShlokRathod 你这是什么意思?此外,这似乎是一个与您在此处提出的问题完全无关的问题。我建议你问一个新问题。请在该问题中添加足够的细节,以便其他人了解所需的行为应该是什么。
猜你喜欢
  • 1970-01-01
  • 2014-10-31
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多