How to connect Objective-C initWithError: method in Swift

I have a class defined in Objective-C whose initiator is -initWithError: (the initializer may fail due to an external resource dependency). I want this to move to Swift as init() throws . The regular initializer inherited from NSObject, -init , can be marked as inaccessible, since I do not want it to be used.

In Objective-C, I have:

 @interface Foo : NSObject - (instancetype _Nullable)initWithError:(NSError **)error; @end 

This works fine in Objective-C, of ​​course.

In Swift, -initWithError closes as init(error: ()) throws . This is likely due to the fact that removing withError: from the method name leads to init() , which conflicts with the inherited simple -init initializer. This can be called from Swift as follows:

 let foo = try Foo(error: ()) 

It looks weird because the error parameter is invalid. It would be better if it were imported as init() throws . The obvious solution is to mark -init with NS_UNAVAILABLE in the Objective-C header. Unfortunately this does not work. -initWithError: still becomes a bridge like init(error: ()) , and trying to call try Foo() results in a compiler error saying that init() not available in Swift.

Is there a more elegant solution for this so try init() just works?

+5
source share
1 answer

You can rename a function using NS_SWIFT_NAME . In this case:

 - (instancetype _Nullable)initWithError:(NSError **)error NS_SWIFT_NAME(init()); 

However, this seems like a compiler error. I suggest opening a defect.

+4
source

Source: https://habr.com/ru/post/1276074/


All Articles