Very new to this and require help

Firstly Hello Everyone - I am having a few issues with an app I am trying to do for my personal use (I have never done coding) I got Chat GPT to do the coding but it has a few issues, from what I can tell this is an issue with the Face ID part of it but I have no clue how to fix it, would someone please help

the issue says the following
"Cannot use mutating member on immutable value: 'self' is immutable"
Many Thanks
Tom
import SwiftUI
import LocalAuthentication
import SwiftUICore
import SwiftUI

struct SettingsView: View {
@State private var faceIDEnabled = false
@State private var isAuthenticated = false

var body: some View {
    NavigationView {
        Form {
            Toggle("Enable Face ID Lock", isOn: $faceIDEnabled)
                .onChange(of: faceIDEnabled) { value in
                    if value {
                        authenticate()
                    }
                }

            if isAuthenticated {
                Text("Face ID authentication successful ✅")
                    .foregroundColor(.green)
            }
        }
        .navigationTitle("Settings")
    }
}

mutating func authenticate() {
    let context = LAContext()
    var error: NSError?

    if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
        let reason = "Secure your job data with Face ID"

        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authError in
            DispatchQueue.main.async {
                self.isAuthenticated = success
                if !success {
                    self.faceIDEnabled = false
                }
            }
        }
    } else {
        self.faceIDEnabled = false
    }
}

}

There is no need to mark authenticate as mutating as you are not actually mutating your SettingsView. You are only mutating the @State in the view, which has a nonmutating set and so does some trickery under the hood to mutate a reference of the state.

1 Like

Hi Tom, I would recommend against using chatGPT to code for you if you're not exactly sure what it's doing. In order to understand an error in generated code you need to understand many new concepts at once. Swift is a great first language because its deliberately made to slowly expose you to its complexities as you use it. In this case:

A common concept in programming is mutability. Its basically just whether something can be changed after it has been created. SwiftUI views are immutable. This means that when you call authenticate, which you told it was mutating, it wont work.

4 Likes