I got the solution but can't understand why it works.
my struct is QuizBrain()
whenever i try to use this code, i got an error:
Cannot use mutating member on immutable value: function call returns immutable value
btw the checkAnswer method is mutated.
code:
let userGotItRight = QuizBrain().checkAnswer(pressedAnswer)
The solution is creating an object from that struct and using it. Can someone explain why it is necessary to create an object?
code:
var quizBrain = QuizBrain()
let userGotItRight = quizBrain.checkAnswer(pressedAnswer)
It is actually mix of
letvsvarandclassvsstruct. Here are some examples. Firstly lets declare your code as bothstructandclass:In this example we I will use
QuizBrainStruct()andQuizBrainClass()which are similar but not the same. YourQuizBrain()is defined as struct, therefore if you make this statement:It is basicelly treated the same way as declaring
letvariable and then calling the function on in as following:Your workoroud works if you declare it as a var, because values of var can be mutated:
However there is more into the topic and that is that
Structis passed as value, therefore "s" cannot be mutated. If you declare it as a class (which is passed as reference) . You can do the following with no errors:Here is the difference why:
For more info about struct vs class you can read following swift doc . You can read more about value and reference type here: value vs reference passing