🔒 Swift 6 中让 Any 类型遵循 Sendable 协议
Swift
2026-03-17
问题背景
在 Swift 6 的严格并发检查模式下,Any 类型默认不遵循 Sendable 协议,会导致编译警告或错误:
⚠️ Type 'Any' does not conform to protocol 'Sendable'
解决方案
使用 any Any & Sendable 来明确声明类型既可以是任意类型,又遵循 Sendable 协议:
// ❌ Swift 6 下会报错
var data: Any
func processData(_ input: Any) { }
// ✅ 正确写法
var data: any Any & Sendable
func processData(_ input: any Any & Sendable) { }
使用场景
- 属性声明:
var value: any Any & Sendable - 函数参数:
func handle(_ data: any Any & Sendable) - 闭包捕获:
let callback: (any Any & Sendable) -> Void - 泛型约束:
struct Container
💡 语法说明:
any关键字表示存在类型(existential type)Any & Sendable表示类型必须同时满足 Any 和 Sendable- 组合写法:
any ProtocolA & ProtocolB
⚠️ 注意:
- Swift 6 默认启用严格并发检查
- 如果确定类型是线程安全的,可以使用
@unchecked Sendable绕过检查 - 但对于
Any类型,推荐使用any Any & Sendable明确约束
✅ 完整示例:
class DataManager: @unchecked Sendable {
// 存储任意 Sendable 类型的数据
var cache: [String: any Any & Sendable] = [:]
// 接收 Sendable 参数
func store(_ value: any Any & Sendable, forKey key: String) {
cache[key] = value
}
// 返回 Sendable 类型
func retrieve(forKey key: String) -> (any Any & Sendable)? {
return cache[key]
}
}