我有两个 C 函数:
extern UIColor* LNRandomDarkColor();
extern UIColor* LNRandomLightColor();
作为练习,我尝试将它们作为 UIColor
的扩展方法导入到 Swift 中。
以下是 Apple 在 WWDC 2016 上的“Swift 新功能”演示文稿示例:
void CGContextFillPath(CGContextRef) NS_SWIFT_NAME(CGContext.fillPath(self:));
我试图以类似的方式注释我的函数:
extern UIColor* LNRandomDarkColor() NS_SWIFT_NAME(UIColor.randomDarkColor());
extern UIColor* LNRandomLightColor() NS_SWIFT_NAME(UIColor.randomLightColor());
但是我收到以下警告:
'swift_name' attribute can only be applied to function declarations with prototypes
我在这里做错了什么?
更新:打开SR-2999对于这个问题。
最佳答案
这是部分结果。以下代码 – 从以下示例创建 SE-0044 Import as member – 编译:
struct MyColor { };
UIColor * _Nonnull LNRandomDarkColor(void)
__attribute__((swift_name("MyColor.randomDarkColor()")));
并将 C 函数导入为 MyColor
的静态成员函数
键入 Swift:
let col = MyColor.randomDarkColor()
但是我无法将函数作为成员函数导入
任何现有类型,如UIColor
:
UIColor * _Nonnull LNRandomDarkColor(void)
__attribute__((swift_name("UIColor.randomDarkColor()")));
// warning: imported declaration 'LNRandomDarkColor' could not be mapped to 'UIColor.randomDarkColor()'
(并且 UIColor.randomDarkColor()
不编译)。我不知道这是有意限制还是错误。
使用 NS_SWIFT_NAME
宏代替 swift_name
属性也不起作用:
UIColor * _Nonnull LNRandomDarkColor(void)
NS_SWIFT_NAME("MyColor.randomDarkColor()");
// warning: parameter of 'swift_name' attribute must be a Swift function name string
关于swift - NS_SWIFT_NAME 用于将 C 函数导入为类扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40133453/