[英]Can I use NS_SWIFT_NAME or NS_REFINED_FOR_SWIFT on a C enum to map a global function to a Swift property?
I have an enum like我有一个枚举
typedef NS_ENUM(NSInteger, MyEnum) {
MyEnumCase1,
MyEnumCase2,
...
};
and a function that maps those enum values to arbitrary strings以及将这些枚举值映射到任意字符串的 function
FOUNDATION_EXPORT NSString *myEnumString(MyEnum val);
Is it possible to expose this to Swift as a property?是否可以将其作为属性公开给 Swift?
I've tried我试过了
FOUNDATION_EXPORT NSString *myEnumString(MyEnum val) NS_SWIFT_NAME(MyEnum.stringVal);
but the compiler gives me the warning "'swift_name' attribute argument must be a string literal specifying a Swift function name" and Swift callers don't see stringVal
as a property on values of MyEnum
.但编译器给我警告“'swift_name' 属性参数必须是字符串文字,指定 Swift function 名称”和 Swift 调用者不会将
stringVal
视为MyEnum
值的属性。
and I've tried我试过了
FOUNDATION_EXPORT NSString *myEnumString(MyEnum val) NS_REFINED_FOR_SWIFT;
but my Swift extension但我的 Swift 分机
extension MyEnum {
var stringVal {
return __myEnumString(self)
}
}
can't find __myEnumString()
.找不到
__myEnumString()
。
The Swift function name passed to NS_SWIFT_NAME
must include the implicit self:
argument, and to import it as a read-only property (instead of a method), "getter:" must be prepended.传递给
NS_SWIFT_NAME
的 Swift function 名称必须包含隐式self:
参数,并且要将其作为只读属性(而不是方法)导入,必须在前面加上“getter:”。 Various examples can be found in SE-0044 Import as member .可以在SE-0044 Import as member中找到各种示例。
So the correct syntax to expose the C function as a (read-only) property to Swift is因此,将 C function 作为(只读)属性公开给 Swift 的正确语法是
NSString *myEnumString(MyEnum val)
NS_SWIFT_NAME(getter:MyEnum.stringVal(self:));
The generated Swift interface is生成的Swift接口为
extension MyEnum {
public var stringVal: String { get }
}
and this compiles and runs as expected in my test:这在我的测试中按预期编译和运行:
print(MyEnum.case1.stringVal)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.