Swift 并发修改Sendable 闭包



Swift 5.5 引入了 Sendable 协议和并发模型,使得在 Swift 中编写并发代码变得更加容易和直观。Sendable 协议用于表示类型可以安全地在多个线程之间传递。

在 Swift 的并发模型中,闭包(closures)经常用于异步操作。为了使闭包在并发环境中安全使用,它们需要满足 Sendable 协议。

下面是如何修改一个闭包以使其满足 Sendable 协议的示例:

import Foundation  
  
// 定义一个不满足 Sendable 协议的闭包  
let nonSendableClosure: () -> Void = {  
    print("Hello from non-sendable closure!")  
}  
  
// 尝试在 Task 中使用不满足 Sendable 协议的闭包将会导致编译错误  
Task {  
    nonSendableClosure() // Error: Closure containing controlling capture '[weak self]' cannot be sent between threads; consider making it 'Sendable' by capturing 'self' strongly (if safe) or making the capture 'unowned' if you can guarantee the closure will never be called after 'self' has been deallocated  
}  
  
// 修改闭包以满足 Sendable 协议  
let sendableClosure: @Sendable () -> Void = {  
    print("Hello from sendable closure!")  
}  
  
// 现在闭包可以在 Task 中安全使用  
Task {  
    sendableClosure() // This works!  
}

在上面的示例中,我们首先定义了一个不满足 Sendable 协议的闭包。当我们尝试在 Task 中使用这个闭包时,编译器会报错。为了解决这个问题,我们使用了 @Sendable 属性来修饰闭包,使其满足 Sendable 协议。这样,闭包就可以在 Task 中安全使用了。