简体   繁体   中英

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.

For instance, an Objective-C method with this definition

-(void)logProductWithId:(NSString *) productId productName:(NSString*) productName;

is automatically translated to this Swift function

func logProductWithId(productId: String, productName: String)

Is it a good habit to use the NS_SWIFT_NAME macro to get rid of the "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. The Apple documentation mentions only factory methods as example but does not explicitly say that about a restriction on NS_SWIFT_NAME

There's no clear restriction in Apple's documentation as far as I can find. 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.

Seems NS_SWIFT_NAME is not reserved only for factory methods. And better use it to make your Objective-C code more Swift-friendly. And please do not forget to put nullability attributes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM