SwiftUI | How to fix “Cannot assign to property: ‘self’ is immutable”

SwiftUI

This article describes how to fix “Cannot assign to property: ‘self’ is immutable”.

Conclusion

Add @State to the variable you want to change.

Example

Let’s take an example of an App that reduces HP when attacking Yoshihiko. Since Yoshihiko’s HP is variable, it is necessary to add @State.

OK example

Add @State to variable YoshihikoHP.

import SwiftUI

struct ContentView: View {
    @State var YoshihikoHP: Int = 100 // ?
    var body: some View {
        Text("Yoshihiko HP:" + String(YoshihikoHP))
        Button("Attack Yoshihiko") {
            YoshihikoHP -= 10
        }
        .buttonStyle(.borderedProminent)
    }
}

NG example

Do not add @State to variable YoshihikoHP.

import SwiftUI

struct ContentView: View {
    var YoshihikoHP: Int = 100 // ? NG
    var body: some View {
        Text("Yoshihiko HP:" + String(YoshihikoHP))
        Button("Attack Yoshihiko") {
            YoshihikoHP -= 10
        }
        .buttonStyle(.borderedProminent)
    }
}

Summary

This article described how to fix “Cannot assign to property: ‘self’ is immutable”.

コメント

タイトルとURLをコピーしました