1

I'm trying to write a simple quiz app. Upon a user tapping a button, I want the action to compare the Button's label to see if it matches the variable of "correctChoice"

I tried the following if/then statement but it doesn't seem to work, as I'm getting the following error "Left side of mutating operator isn't mutable: 'self' is immutable"

//Variables Used

var model = Question.all()
var questionNumber: Int = 1
var totalQuestions: Int = 100
var timeLeft: Int = 60
var currentScore: Int = 0

//Button Code

Button(action: {
                 if Question.all()[0].choice1 == Question.all()[0].correctChoice {
                            currentScore += 10
                        } else {
                            currentScore += 0
                        }  
                    }) {
                        Text(Question.all()[0].choice1)
                            .font(.system(size: 20))
                    }
2
  • 1
    As mentioned in the correct answer, you probably should put all of this in a model. (That's why I'm adding a comment along with the upvote.) Consider this: (1) Your model is simply two (or more) ObservableObject classes of type Question and Player. (2) You can expose this as either an EnvironmentObject or ObservedObject. (3) Properly done it maintains state. Conclusion? To "interact" between SwiftUI and your "variable" - which is not a UI element but instead something stored - you need to make it "mutable" to SwiftUI by making it @State. Commented Sep 9, 2019 at 20:30
  • Thanks for the follow-up. I'm new to coding, I'm a UX designer. I definitely will read up on Objects. Currently, I only have the questions and answers in my model. Commented Sep 9, 2019 at 20:44

1 Answer 1

2

currentScore should be a @State variable to be mutable inside a struct. Or it can be inside a model.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.