是否有一种通用的方法来处理swift中async和throws的组合



我发现关于快速并发的文档很少,所以我发现我必须构建大多数自己的异步工具,尽管它们可能已经存在于某个地方。

然而,在大多数情况下,我需要制作四个基本相同功能的副本。例如,假设我想要一个真正合适的异步";在这个长"-"的延迟之后运行函数我最终使用

//
// do this after this amount of time
//
public static func after<T>( ms : Int, function : () -> T) async -> T
{
await delay(ms: ms)
return function()
}
//
// do this after this amount of time
//
public static func after<T>( ms : Int, function : () throws -> T) async throws -> T
{
await delay(ms: ms)
return try function()
}
//
// do this after this amount of time
//
public static func after<T>( ms : Int, function : () async -> T) async -> T
{
await delay(ms: ms)
return await function()
}

//
// do this after this amount of time
//
public static func after<T>( ms : Int, function : () async throws -> T) async throws -> T
{
await delay(ms: ms)
return try await function()
}

所以我想知道是否有任何方法可以在一个函数中这样说——基本上是说";并且它应该与具有async/show"的任意组合的函数一起工作;

您可以简单地将此语法用于最通用的解决方案:

func after<T>(ms: Int, function: () async throws -> T) async rethrows -> T {
delay(ms: ms)
return try await function()
}

rethrows:仅当内部函数抛出时抛出

async:您还可以向异步部分传递一个同步函数;没关系

示例:

// No error thrown (no need for try); function is not async
let a = await after(ms: 10) { return 1 }
// No error thrown; function is async
let b = await after(ms: 10) { return await after(ms: 20) { return 2 } }
// Error thrown (try needed); function is not async
let c = try await after(ms: 10) { throw NSError() }
// Error thrown; function is async
let d = try await after(ms: 10) { return try await after(ms: 20) { throw NSError() } }

最新更新