Ben Butterworth
Ben Butterworth

Reputation: 28512

In Swift, an Objective-C BOOL inferred as `()` instead of Bool

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:

Upvotes: 0

Views: 506

Answers (1)

Sulthan
Sulthan

Reputation: 130102

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)

Upvotes: 3

Related Questions