1

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.

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.