[英]Is NS_SWIFT_NAME reserved to Factory methods?
I'm working on a library written in Objective-C and I would like to make it as "Swifty" as possible when bridged on Swift. 我正在开发一个用Objective-C编写的库,我想在Swift上桥接时尽可能使它成为“Swifty”。
For instance, an Objective-C method with this definition 例如,具有此定义的Objective-C方法
-(void)logProductWithId:(NSString *) productId productName:(NSString*) productName;
is automatically translated to this Swift function 自动转换为此Swift函数
func logProductWithId(productId: String, productName: String)
Is it a good habit to use the NS_SWIFT_NAME
macro to get rid of the "With": 使用NS_SWIFT_NAME
宏来摆脱“With”是一个好习惯:
-(void)logProductWithId:(NSString *) productId productName:(NSString*) productName NS_SWIFT_NAME( logProduct(identifier:name:) )
which is then translated in swift to 然后迅速翻译成
func logProduct(identifier productId: String, name productName: String)
I see some SO questions mentioning that NS_SWIFT_NAME
is available only for factory methods. 我看到一些SO问题,提到NS_SWIFT_NAME
仅适用于工厂方法。 The Apple documentation mentions only factory methods as example but does not explicitly say that about a restriction on NS_SWIFT_NAME
Apple文档仅提及工厂方法作为示例,但没有明确说明有关NS_SWIFT_NAME
的限制
There's no clear restriction in Apple's documentation as far as I can find. 据我所知,Apple的文档中没有明确的限制。 Let's make it a try. 我们试一试吧。
A sample project including this code: 包含此代码的示例项目:
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
-(void)logProductWithId:(NSString *) productId productName:(NSString*) productName NS_SWIFT_NAME( logProduct(identifier:name:) );
@end
Compiles successfully, and you can see its generated interface as: 编译成功,您可以将其生成的界面视为:
import Foundation
open class MyClass : NSObject {
open func logProduct(identifier productId: String!, name productName: String!)
}
No problem. 没问题。 Maybe you need some other condition to get "Only factory methods can have 'swift_name' attribute" error, which I have not revealed yet. 也许你需要一些其他条件来获得“只有工厂方法可以有'swift_name'属性”错误,我还没有透露。
Seems NS_SWIFT_NAME
is not reserved only for factory methods. 似乎NS_SWIFT_NAME
不仅为工厂方法保留。 And better use it to make your Objective-C code more Swift-friendly. 并且更好地使用它来使您的Objective-C代码更加Swift友好。 And please do not forget to put nullability attributes. 请不要忘记放置可空性属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.