0

I've got a method written in Objective-C which returns a BOOL, for example:

 (BOOL)methodName:(NSDictionary<NSString *, NSString *> *)params callback:(void(^)(NSString *_Nullable, ErrorInformation *_Nullable))callback error:(NSError *_Nullable *_Nullable)errorPtr;

Usage in Swift

I get the error, Cannot convert value of type '()' to expected condition type 'Bool'. I thinks that ret is of type (), instead of BOOL. Looking at the implementation, this value is mutated inside dispatch_sync.

let ret = try! methodName()
// I've tried a bunch of different syntaxes below:
if (ret) { <--- Xcode warning: Cannot convert value of type '()' to expected condition type 'Bool'

}

It is not nice to see this method has 3 ways of indicating failure, but I didn't design it and frankly my objective-C is not good:

  • errorPtr, which is automatically turned into do/try/catch in Swift
  • ErrorInformation passed in the callback
  • BOOL return value, which I am struggling with.
Ben Butterworth
  • 22,056
  • 10
  • 114
  • 167

1 Answers1

3

The returned BOOL is part of the NSError processing that is converted in Swift into a throws function (if the method returns a value, Swift will convert it from nullable to nonnull).

YES is returned if the method succeeds (there is no error), NO is returned when the method fails.

In Swift:

do {
   try methodName()
   // method succeeded
} catch {
  // method failed
}

The ErrorInformation in the callback is probably related to asynchronous errors, probably similar to a Result<String, Error> in Swift.

References:

  1. Handling Error Objects Returned From Methods (Obj-C)
  2. Improved NSError Bridging (Swift Evolution 0112)
Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • Thanks! Could you point me to the docs for the `NSError` processing? I wanted to understand why in Objective-C the API would both have `ret` (BOOL return value) and a `nsError` pointer. – Ben Butterworth Aug 19 '21 at 19:37
  • 1
    @BenButterworth Added references :) In short, you would use the returned value for a fast check success/fail and you would use the error parameter if you wanted to know the exact error. You could pass `NULL` to the error parameter. – Sulthan Aug 19 '21 at 19:40
  • 2
    "why in Objective-C the API would both have ret (BOOL return value) and a nsError pointer" Because the pointer might be non nil on success. So in Objective C first you look at the Bool, and if NO you look at the error. That's tricky. Whole point is that Swift wraps it for you. – matt Aug 19 '21 at 19:44