Calling Mutating Async Functions from SwiftUI Views #7
diegolavalledev
announced in
Posts
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Originally published on diegolavalle.com.
Whenever we try to make a call from a SwiftUI view to a mutating asynchronous function on a struct, we are greeted with an error message similar to this one:
Cannot call mutating async function 'someFunction()' on actor-isolated property 'someStruct'.
Let's assume we have the following data structure design which allows us to unlock an app with a three second delay:
Now suppose we want to call the async mutating function
unlock()
from a SwiftUI view:As it is, we'll get the familiar error:
Cannot call mutating async function 'unlock()' on actor-isolated property 'appData'.
To work around this issue we can simply add a proxy function to our
struct
'sBinding
type which will in turn call the original mutating function. It's important that we mark this extension@MainActor
to avoid the infamous purple error reminding us that publishing changes from background threads is not allowed.Now we can simply modify the original call site and add a
$
sign toappData
to access the binding and call our proxy.This technique allows us to continue to leverage value types and incorporate even more sophisticated logic into our models.
Beta Was this translation helpful? Give feedback.
All reactions