如何用Swift 5.9参数包实现主线程闭包并解决编译错误?
Swift 5.9 参数包实现主线程闭包类型的问题修复
针对你遇到的两个编译错误,以下是具体修复方案:
错误原因与修复要点
- 类型歧义错误:编译器无法自动推断参数包闭包的具体类型,同时GCD的异步调用要求闭包满足
@Sendable并发安全约束,添加该标注即可消除歧义。 - 参数包传递错误:调用闭包时需要用
repeat关键字展开参数包,而非直接使用each parameter。
修正后的完整代码
public struct MainClosure<each T> { private let closure: @Sendable (repeat each T) -> Void public init(_ closure: @escaping @Sendable (repeat each T) -> Void) { self.closure = closure } public func callAsFunction(_ parameter: repeat each T) -> Void { DispatchQueue.main.async { self.closure(repeat each parameter) } } }
验证使用
你的示例代码可以正常运行,调用completion(.success("foo"))时,闭包会自动切换到主线程执行:
protocol Repository { func loadData(completion: MainClosure<Result<String, Error>>) } class MockRepository: Repository { func loadData(completion: MainClosure<Result<String, Error>>) { DispatchQueue.global().async { // 模拟数据加载逻辑 completion(.success("foo")) } } }
内容的提问来源于stack exchange,提问作者Guy Kogus
相关产品推荐
相关产品推荐

