简体   繁体   English

如何设置抛出错误的分离任务

[英]How to setup a detached task that throws an error

I'm trying to create a detached task that can throw an error.我正在尝试创建一个可能引发错误的分离任务。 Here's a synthesized example of what I have.这是我所拥有的综合示例。

 @MainActor
  var eventHandlerTask: Task<(), Never>? = nil

  func eventsHandler(events: [BEIEvent]) async throws {
    eventHandlerTask = Task.detached { [weak self] in
       throw NSError()
    }
  }

Xcode complains with: Invalid conversion from throwing function of type '@Sendable () throws -> Bool' to non-throwing function type '@Sendable () async -> Bool' Xcode 抱怨:从抛出类型“@Sendable () throws -> Bool”的 function 到非抛出类型“@Sendable () async -> Bool”的无效转换 function

在此处输入图像描述

How can I setup a detached task that throws?如何设置抛出的分离任务?

You have defined eventHandlerTask to have a Failure type of Never .您已将eventHandlerTask定义为具有NeverFailure类型。 So it cannot throw an error.所以它不能抛出错误。

However, if you change Never to Error , then it can take a closure that throws errors:但是,如果您将Never更改为Error ,那么它可能会采取抛出错误的闭包:

var eventHandlerTask: Task<(), Error>?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM