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?
source share