Now you have the opposite problem. You are asking about arrays, but your problem has nothing to do with them specifically.
Array
is a value type in Swift, and your problem revolves around value type mutation.
struct ContentView: View {
var mutable = 0
var body: some View {
mutable = 1 // Cannot assign to property: 'self' is immutable
EmptyView()
}
}
Take SwiftUI away for a moment. Your problem reduces to this:
struct ValueType {
var mutable = 0
var property: Void {
mutable = 1 // Cannot assign to property: 'self' is immutable
return // The return type is irrelevant to the problem.
}
}
Property get
accessors cannot mutate self
. By default, get
is nonmutating. All of these are the same. The first two are shorthand for the full form, nonmutating get
.
struct ValueType {
var property: Void { return }
}
struct ValueType {
var property: Void {
get { return }
}
}
struct ValueType {
var property: Void {
nonmutating get { return }
}
}
To compile, the get
must be mutating
, instead.
struct ValueType {
var mutable = 0
var property: Void {
mutating get {
mutable = 1
return
}
}
}
But SwiftUI's View
protocol requires that body be nonmutating
.
- If you're going to use SwiftUI, you instead use property wrappers like
@State
and@Binding
to mutate the variables that are associated with aView
. body
is not a place to perform imperative code. Imperative code is not compatible withViewBuilder
, whichbody
uses. There are many correct options available, but which one is appropriate is dependent on use case.
struct ContentView: View {
@State var int = 0
var body: some View {
int = 1 // 'buildExpression' is unavailable: this expression does not conform to 'View'
EmptyView()
}
}