UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Problem with a little side project between days

Forums > SwiftUI

Since tomorrow I am writing part two of Guess the flag and I wanted to practise swift I wrote a guess the number game. All works, except my "Reset()" function. Why, if I call it instead of a print the compiler tells me that self is immutable, even though all properties changed with my function are indeed mutable? Code below

//
//  ContentView.swift
//  StupidGame
//
//  Created by Arkadiusz Świętnicki on 30/05/2022.
//

import SwiftUI

struct ContentView: View {
    @State private var enteredValue = 1
    @State private var shouldShowAlert = false
    @State private var maxGuesses = 10
    @State private var numberToGuess = Int.random(in: 1...100)
    @State private var result = false
    func judgeGuess(_ guess: Int) -> Bool {
        if guess == numberToGuess {
            return true
        }
        return false
    }
    mutating func resetGame() {
        numberToGuess = Int.random(in: 1...100)
        maxGuesses = 10
        enteredValue = 1
    }
    var body: some View {
        Form {
            Section {
                TextField("Number to guess", value: $enteredValue, format: .number).keyboardType(.numberPad)
            } header: {
                Text("Enter a number between 1 and 100")
            }
            Button("Validate") {
                result = judgeGuess(enteredValue)
                if result == false {
                    maxGuesses -= 1
                    if maxGuesses <= 0 {
                        print("Game Over")
                    }
                }
                shouldShowAlert = true
            }.alert("You \(result ? "win" : "lose")", isPresented: $shouldShowAlert) {
                Button("OK") {}
            } message: {
                if enteredValue == numberToGuess {
                    Text("Well done!")
                }
                Text("Your number is \(enteredValue < numberToGuess ? "less than" : "more than") the number assigned by the system. Keep trying!")
            }
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2      

P.S. I accidentally posted in the wrong forum. Sorry!

2      

Because self in the action closure of the Button is immutable. If you change your Button's action closure to this:

Button("OK") {
    var s = self
    s.resetGame()
}

you will see that the error goes away. But then you end up with the problem that self and s are not the same structs because structs are value types and so s is a mutable copy, not the immutable original. So we don't want to do this.

But remove mutating from in front of the resetGame function and your code will work.

even though all properties changed with my function are indeed mutable

They are marked as @State, which does make them mutable, but the struct itself is not. State properties are handled differently than regular properties and are stored outside of the struct's memory. Changing them is allowed even though the struct is immutable because of the different way they are stored. Technically, when you change a property marked as @State, you aren't changing the View struct they are in, you are changing the value that is stored externally to that struct; the struct just reads those @State properties to get their current values. Make sense?

2      

Almost. Why removing "mutating" helps? What exactly happens?

2      

When you annotate a function with mutating, you tell the compiler that the funnction can change the struct's properties. But since self in that closure is immutable, you can't change the properties, so the compiler complains that you are trying to call a function that can make changes in a context where changes cannot be made. Removing mutating makes the compiler happy.

And in this case, mutating is not needed anyway (becuase of the @State explanation I gave above), so you can safely remove it.

4      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.