Swift error: Cannot convert value of type '() throws -> ()' to specified type 'Bool'

Swift error: Cannot convert value of type '() throws -> ()' to specified type 'Bool'

我在 Objective C 中有一个函数 returns 一个 BOOL 并且有一个 errorOut 参数。 swift 桥按预期将 errorOut 参数转换为 throws,但它也停止返回 BOOL

我可以看到通常返回 BOOL 以指示 success/error 但在这种情况下实际上需要布尔值。我需要进行哪些更改才能确保返回布尔值?

Objective C 函数签名

- (BOOL)hasAnyData:(NSError *__autoreleasing *)errorOut;

感谢@MartinR 链接到 similar question,我在其中找到了这个技巧:

将 Objective C 函数声明更改为

- (BOOL)hasAnyData:(NSError *__autoreleasing *)errorOut __attribute__((swift_error(nonnull_error)));

然后从 Swift 调用它,例如

let hasAnyData: Bool = try self.repo.hasAnyThings()

完全符合我的要求!

swift_error 属性记录在此处:https://github.com/apple/swift-clang/blob/383859a9c4b964af3d127b5cc8abd0a8f11dd164/include/clang/Basic/AttrDocs.td#L1800-L1819


原始答案 - 没有完全解决问题,但可能对查看此问题的其他人有用,因为它在类似情况下很有用。

我终于在 Swift 文档中找到了这个:

Use the NS_SWIFT_NOTHROW macro on an Objective-C method declaration that produces an NSError to prevent it from being imported by Swift as a method that throws.

我现在已经在我的 Objective C 函数声明中添加了一个 NS_SWIFT_NOTHROW 注释,例如

- (BOOL)hasAnyData:(NSError *__autoreleasing *)errorOut NS_SWIFT_NOTHROW;

我必须从 Swift

传入 NSError pointer
var error: NSError?
let hasAnyData = self.repo.hasAnyData(&error)

这不是最好的,因为我无法再快速处理错误(使用 do, try catch 而必须使用 NSError),但它是我能找到的最好的。