How to fix “Cannot assign to property: 'self' is immutable”
2022년 12월 1일About 2 min
How to fix “Cannot assign to property: 'self' is immutable” 관련
SwiftUI by Example
Back to Home
How to fix “Cannot assign to property: 'self' is immutable” | SwiftUI by Example
How to fix “Cannot assign to property: 'self' is immutable”
Updated for Xcode 15
SwiftUI’s views should be structs, which means they are immutable by default. If this were our own code we could mark methods using mutating
to tell Swift they will change values, but we can’t do that in SwiftUI because it uses a computed property.
If you want to change a property’s value while your program runs, you should mark it using @State
, like this:
@State private var runCount = 0
For more complex properties, such as reference types or values that are shared across multiple views, you should use @StateObject
, @ObservedObject
or @EnvironmentObject
instead.
Similar solutions…
How to fix “Cannot convert value of type 'String' to expected argument type 'Binding'” | SwiftUI by Example
How to fix “Cannot convert value of type 'String' to expected argument type 'Binding'”
How to fix “Cannot convert value of type 'String' to expected argument type 'Text'” | SwiftUI by Example
How to fix “Cannot convert value of type 'String' to expected argument type 'Text'”
How to fix “Cannot convert value of type '() -> ()' to expected argument type '() -> _'” | SwiftUI by Example
How to fix “Cannot convert value of type '() -> ()' to expected argument type '() -> _'”
How to fix “Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements” | SwiftUI by Example
How to fix “Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements”
How to fix “Property declares an opaque return type, but has no initializer expression from which to infer an underlying type” | SwiftUI by Example
How to fix “Property declares an opaque return type, but has no initializer expression from which to infer an underlying type”