throw an error in Swift, catch in Objective C

@objc(XMPLOurService) 
public class OurService : NSObject {
     public class func isSomething( param: String? )  -> Bool { ...


In a mixed language iOS project this correctly populates the bridging header and can be called from objective C.


But I want to throw an error from this code so I change this to say:


@objc(XMPLOurService)
public class OurService : NSObject {
     public class func isSomething( param: String? ) throws -> Bool { ...


And now the function disappears from the bridging header and can't be called from objective C.


What am I doing wrong?

Answered by OOPer in 197537022

When Swift exports throws-function to Ojective-C, it does two things:


  • Add an extra parameter taking a nullable pointer to `NSError*`.
  • Change the return type to Optional, if the return type is Void, it is chnaged to `BOOL`.


So, in your case, Swift tries to convert the return type to something like `bool?`, but unfortunately, Optional-primitive types cannot be represented in Objective-C.

Thus, Swift gives up exporting the method to Objecive-C.


You can try something like this:

    public class func isSomethingOther( param: String? ) throws {
        //...
    }

or like this:

    public class func isSomethingAnother( param: String? ) throws -> NSNumber {
        //...
        return true as NSNumber
    }
Accepted Answer

When Swift exports throws-function to Ojective-C, it does two things:


  • Add an extra parameter taking a nullable pointer to `NSError*`.
  • Change the return type to Optional, if the return type is Void, it is chnaged to `BOOL`.


So, in your case, Swift tries to convert the return type to something like `bool?`, but unfortunately, Optional-primitive types cannot be represented in Objective-C.

Thus, Swift gives up exporting the method to Objecive-C.


You can try something like this:

    public class func isSomethingOther( param: String? ) throws {
        //...
    }

or like this:

    public class func isSomethingAnother( param: String? ) throws -> NSNumber {
        //...
        return true as NSNumber
    }
throw an error in Swift, catch in Objective C
 
 
Q