为何Swift中"+"运算符未标记Sendable?AsyncSequence代码警告求解
问题原因
Swift标准库中针对Int的+运算符并未被显式标记为@Sendable,而AsyncSequence的scan(_:_:)方法要求传入的累加器函数必须是@Sendable类型——因为AsyncSequence用于异步并发场景,@Sendable可保证函数能安全跨执行体传递,不会引入数据竞争。
直接传入+时,编译器会尝试将这个非@Sendable的函数转换为@Sendable类型,因此触发警告;而使用闭包{ $0 + $1 }时,编译器会自动推断该闭包符合@Sendable要求(闭包仅对值类型执行加法操作,未捕获任何可变共享状态),所以警告消失。
非侵入式修复方法
以下几种方法无需修改Swift标准库,即可解决警告:
显式标记闭包为@Sendable
在闭包前添加@Sendable修饰,让代码意图更清晰:let emittedSummationSequence = asyncSequence .scan(0, { @Sendable $0 + $1 })自定义@Sendable的加法函数
在自身代码中定义一个标记了@Sendable的加法函数,再传入scan:@Sendable func sendableAdd(_ a: Int, _ b: Int) -> Int { a + b } let emittedSummationSequence = asyncSequence .scan(0, sendableAdd)扩展Int添加@Sendable的静态方法
通过扩展Int类型添加符合@Sendable要求的静态加法方法,复用性更强:extension Int { @Sendable static func sendableAdd(_ lhs: Self, _ rhs: Self) -> Self { lhs + rhs } } let emittedSummationSequence = asyncSequence .scan(0, Int.sendableAdd)
内容的提问来源于stack exchange,提问作者TheLivingForce
相关产品推荐
相关产品推荐

