如何拼接两个不相关的参数包?Swift编译错误求解
解决Swift中拼接独立参数包的编译错误
问题代码
func foo<each T, each V>( _ param1: repeat each T, closure: (repeat each T, repeat each V) -> Void, _ param2: repeat each V, ) { closure(repeat each param1, repeat each param2) // 编译错误 }
编译错误信息
Pack expansion requires that 'each V' and 'each T' have the same shape
报错原因
直接在同一函数调用中展开两个独立参数包时,Swift编译器会默认要求它们的「形状」(元素数量)一致,将其视为配对的参数包而非拼接的参数包,因此触发错误。
解决方案
借助@_transparent标记的辅助函数,让编译器正确识别参数包的拼接逻辑:
// 透明辅助函数,用于正确拼接两个独立参数包 @_transparent func callClosure<each T, each V>( _ closure: (repeat each T, repeat each V) -> Void, with firstArgs: repeat each T, then secondArgs: repeat each V ) { closure(repeat each firstArgs, repeat each secondArgs) } func foo<each T, each V>( _ param1: repeat each T, closure: (repeat each T, repeat each V) -> Void, _ param2: repeat each V, ) { callClosure(closure, with: repeat each param1, then: repeat each param2) }
@_transparent会让编译器将辅助函数内联到调用点,此时编译器会正确识别两个参数包是按顺序拼接而非配对,从而通过编译。
内容的提问来源于stack exchange,提问作者Roman
相关产品推荐
相关产品推荐

