我有一个Artist类,下面是一个创建新artist并将其插入我的库数组的函数.因为insertToArtists(artist:)是一个异步函数,所以我必须把它包装成Task.但我也希望我的newArtist返回刚刚创建的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
    }
}

但如果我的代码如下所示.它不会正常工作.它似乎在insertToArtist(artist:)之前返回artist.插入后如何返回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)
    }
}

Swift相关问答推荐

日期格式yyyyyy—MM—dd hh:mm:ss +0000到dd MMM,以swift格式表示""""

减go 用SWIFT struct 填充的NSCountedSet

带有文本输入自动大小写修饰符的SwiftUI Textfield问题

如何在AudioKit中实现自定义音效 node ?

为什么ClosedRange<;Int&>包含的速度比预期慢340万倍?

KMM-Swift铸造密封类

使用序列初始化字符串的时间复杂度是多少?

ToolbarItem 包含在动画中但不应该包含在动画中

SwiftUI如何能够在Text中使用字符串字面量来创建LocalizedStringKey?

从 Swift Vapor Server 中调用 ShazamKit

UIButton 配置不更新按钮标题

如何从数据中读取以空结尾的字符串?

在 Swift 5.5 中编写同步和异步函数

展开 List 中的 HStack 以端到端但不是从上到下,因此看起来项目之间有更宽的空间

将项目引用添加到 Swift iOS XCode 项目并调试

为 UIActivityViewController Swift 设置不同的活动项

在 Swift for iOS 中沿圆形路径绘制文本

协议扩展中的where self是什么

在 Swift 中指定 UITextField 的边框半径

如何将 Int 拆分为其各个数字?