Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 304
Jan Avatar asked Mar 12 '23 06:03

Jan


1 Answers

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.

like image 135
OOPer Avatar answered Apr 09 '23 11:04

OOPer