E. Rivera
E. Rivera

Reputation: 10938

Modify SwiftUI @State from a regular class function using Bindings

I am trying to crate a regular class function that takes an optional Binding<Bool> as a parameter. The idea is that the function will modify the boolean to disable/enable a SwitUI View without the need for callback blocks.

The problem is that I can't find the proper way to modify the boolean from within the function.

func executeTask(inProgress: Binding<Bool>? = nil)
{
    inProgress = true // Error
    // ...
    inProgress = false // Error
}

The error:

Cannot assign to value: 'inProgress' is a 'let' constant

I also tried to mimic SwiftUI behavior by creating a @Binding var inProgress: Bool in the class, assign it, and then modify it with no luck.

Also I would be OK with a non-optional 'inProgress' if that helps, but so far it doesn't.

Upvotes: 1

Views: 404

Answers (2)

Mohammad Rahchamani
Mohammad Rahchamani

Reputation: 5220

To change the Binding's value, you should assign the new value to its wrappedValue property.

try this:

func executeTask(inProgress: Binding<Bool>? = nil)
{
    inProgress?.wrappedValue = true
}

Upvotes: 1

Asperi
Asperi

Reputation: 257493

Binding is a special wrapper, which gives access to references stored value via .wrappedValue

Here is fixed variant (tested with Xcode 12)

func executeTask(inProgress: Binding<Bool>? = nil) {
    // optional chain
    inProgress?.wrappedValue = true
}

Upvotes: 1

Related Questions