问题
最近在将 swift 的静态库迁移到 xcframework 形式,达到兼容不同版本 Xcode(Swift 版本不同)。实际实践发现 A 模块在编译成 xcframework 之后再被 B 模块引用编译,会出现以下错误(以 YYImage 为例):
error: 'YYAnimatedImageView' is not a member type of class 'YYImage.YYImage'
其根本原因是模块 A 中存在与模块名称相同的 class 等类型
解决
一番 google 之后发现 Swift 不支持这种命名, 在论坛中很早就有人提过,可以像其他语言一样:
import YYImage as YYImageModule
但一直未解决,目前只能采用如下 workaround 方案
-module-interface-preserve-types-as-written
在 build settings OTHER_SWIFT_FLAGS
中添加 -Xfronted -module-interface-preserve-types-as-written
,让生成的 swiftinterface 文件不进行重写,即不添加模块名,这个方案并不能 100% 解决这个问题,如果定义了 Public 的枚举,swiftinterface 中还是会存在 MouduleA.
这样的前缀。
extension MouduleA.AEnum : Swift.Equatable {}
脚本
通过脚本修 swiftinterface 文件
find ModuleA.xcframework -name "*.swiftinterface" -exec sed -i '' 's/ModuleA.//g' {} +
总结
目前还是只能通过以上 workaround 方式解决这个问题,最好的方案还是修改模块名称,但这对已发布的 framework 有一定的升级成本。这也提醒我们今后在模块命名上要避免与类名冲突。