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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With