I'm trying to initialize a variable (in a ViewModel) with some value from the db using async await introduced in swift 5.5, but I'm getting the error:
Errors thrown from here are not handled
This is the code:
@Published var userWallets: [Wallet]
init() async {
// Get current User
let user = await NetworkController().getUser()
// Publish all wallets
userWallets = try await getUserWallets(user: user)
}
I have tried to wrap it around a Task
but then it says: 'self' captured by a closure before all members were initialized
How to I initialize that value correctly?
In your example, getUserWallets(user:)
can throw. You therefore have two choices on how to deal with this:
init
throw as well:init() async throws {
// ...
userWallets = try await getUserWallets(user: user)
}
This means that you have to deal with the error when initializing your struct or class.
init() async {
// ...
do {
userWallets = try await getUserWallets(user: user)
} catch {
// handle the error here in some way
}
}