I have a class Artist
, and below is a function to create a new artist
and insert it to my library array. Because insertToArtists(artist:)
is a asynchronous function, I have to wrap it in Task
. But I also want my newArtist
to return the artist
just created.
My code is like below, but Xcode told me an error: No 'init' candidates produce the expected contextual result type 'Artist'
func newArtist(name: String, notes: String, artwork: NSImage?) -> Artist {
Task {
let artist = Artist(name: name, notes: notes, artwork: artwork)
await insertToArtists(artist: artist)
return artist
}
}
But if I make my code like this below. It won't work right. It seems that it returns artist
before it's been insertToArtist(artist:)
. How can I return artist
after it's been inserted. I would appreciate your help.
func newArtist(name: String, notes: String, artwork: NSImage?) -> Artist {
let artist = Artist(name: name, notes: notes, artwork: artwork)
Task {
await insertToArtists(artist: artist)
}
return artist
}
func newArtist(
used? – Chandrafunc newArtist(name: ...) async -> Artist
and put it into aTask
on the caller side? – Rozamondfunc newArtist(name: ...) -> Artist
in another function@MainActor func checkCreate()
which is used to update UI. If I usenewArtist(name) async -> Artist
, would it block main thread when some suspension occurred. – Commandeer