Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swiftui Cannot assign to property: 'self' is immutable Error

I'm facing an error says "cannot assign to property" as seen in the preview image.

I get this error when I use the variable inside the struct of View and inside the forEach.

Here's Screenshot.enter image description here

like image 262
Nawaf Avatar asked Jan 22 '20 20:01

Nawaf


People also ask

Is SwiftUI immutable?

SwiftUI views are structs. Structs are immutable by default (so the values inside are immutable too) Methods (functions) marked with mutating can mutate the values of properties. But that's not allowed in SwiftUI, because it uses a computed property.

Are Swift structs immutable?

Yep, you're right, structs are not immutable. The thing about structs is that they are values. That means every variable is considered a copy, and its members are isolated from changes made to other variables. Structs are not copied on mutation.

How do I use the timer in SwiftUI?

If you want to run some code regularly, perhaps to make a countdown timer or similar, you should use Timer and the onReceive() modifier. It's important to use . main for the runloop option, because our timer will update the user interface.

Why does SwiftUI use some view?

First, using some View is important for performance: SwiftUI needs to be able to look at the views we are showing and understand how they change, so it can correctly update the user interface.


1 Answers

Define you currentMood as a @State variable:

@State var currentMood: String

You'll likely need to assign it with self.currentMood = moodData (adding self.)

like image 120
Rob Napier Avatar answered Nov 03 '22 14:11

Rob Napier