如何在 Swift 中的任务中定义 return 变量
How to return variable defined in Task in Swift
我有一个 class Artist
,下面是一个创建新 artist
并将其插入到我的库数组的函数。因为insertToArtists(artist:)
是一个异步函数,所以我得把它包在Task
里面。但我也希望我的 newArtist
到 return 刚刚创建的 artist
。
我的代码如下所示,但是 Xcode 告诉我一个错误: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
}
}
但是如果我像下面这样编写我的代码。它不会正常工作。似乎 return 比 artist
早 insertToArtist(artist:)
。插入后如何return artist
。非常感谢您的帮助。
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
}
嗯,知道如何使用 newArtist
会很有用,但我相信您也需要将其设为异步。
func newArtist(name: String, notes: String, artwork: NSImage?) async -> Artist {
let artist = Artist(name: name, notes: notes, artwork: artwork)
await insertToArtists(artist: artist)
return artist
}
然后在您呼叫 newArtist
的地方使用 Task
func whereYouUseNewArtist() {
//YourCode
Task {
//YourCode
x = await newArtist(name: name, notes: notes, artwork: artwork)
//YourCode
}
//YourCode
}
如果您需要用 newArtist
的结果更新您的 UI,请记住在主线程中进行。您可以通过在使用它的地方添加 @MainActor
来实现。示例:
let artistToShowOnUI: Artist
@MainActor func whereYouUseNewArtist() {
Task {
artistToShowOnUI = await newArtist(name: name, notes: notes, artwork: artwork)
}
}
我有一个 class Artist
,下面是一个创建新 artist
并将其插入到我的库数组的函数。因为insertToArtists(artist:)
是一个异步函数,所以我得把它包在Task
里面。但我也希望我的 newArtist
到 return 刚刚创建的 artist
。
我的代码如下所示,但是 Xcode 告诉我一个错误: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
}
}
但是如果我像下面这样编写我的代码。它不会正常工作。似乎 return 比 artist
早 insertToArtist(artist:)
。插入后如何return artist
。非常感谢您的帮助。
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
}
嗯,知道如何使用 newArtist
会很有用,但我相信您也需要将其设为异步。
func newArtist(name: String, notes: String, artwork: NSImage?) async -> Artist {
let artist = Artist(name: name, notes: notes, artwork: artwork)
await insertToArtists(artist: artist)
return artist
}
然后在您呼叫 newArtist
Task
func whereYouUseNewArtist() {
//YourCode
Task {
//YourCode
x = await newArtist(name: name, notes: notes, artwork: artwork)
//YourCode
}
//YourCode
}
如果您需要用 newArtist
的结果更新您的 UI,请记住在主线程中进行。您可以通过在使用它的地方添加 @MainActor
来实现。示例:
let artistToShowOnUI: Artist
@MainActor func whereYouUseNewArtist() {
Task {
artistToShowOnUI = await newArtist(name: name, notes: notes, artwork: artwork)
}
}