在 Swift 中,一个 Objective-C BOOL 被推断为 `()` 而不是 Bool

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

我有一个用 Objective-C 编写的方法,其中 return 是 BOOL,例如:

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

在Swift

中的用法

我收到错误,Cannot convert value of type '()' to expected condition type 'Bool'。我认为 ret() 类型,而不是 BOOL。查看实现,此值在 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'

}

看到这个方法有3种指示失败的方式并不好,但我没有设计它,坦率地说我的objective-C不好:

返回的 BOOLNSError 处理的一部分,在 Swift 中转换为 throws 函数(如果方法 returns 一个值, Swift 会将其从 nullable 转换为 nonnull).

方法成功返回

YES(无错误),方法失败返回NO

在Swift中:

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

回调中的ErrorInformation可能与异步错误有关,可能类似于Swift中的Result<String, Error>

参考文献:

  1. Handling Error Objects Returned From Methods (Obj-C)
  2. Improved NSError Bridging (Swift Evolution 0112)