ObjC 错误抛出函数返回 () 而不是 BOOL

ObjC error throwing function returning () instead of BOOL

我有一个 Objective C 函数声明为:

+ (BOOL)isScanningUnsupported:(NSError **)error;

如果它 return 是真的,我必须在我调用它的函数中 return nil (Swift)。

所以我这样打电话:

 var isUnsupported = false

 do { try  isUnsupported = PPCoordinator.isScanningUnsupported()
 } catch let error { throw error }

 if isUnsupported {return nil }

但它告诉我:

Cannot assign a value of type '()' to a value of type 'Bool'

在 Objective C 中,它被称为:

if ([PPCoordinator isScanningUnsupported:error]) {
    return nil;
}

我能做什么????

我想你想要:

var isUnsupported = false

 do { try  PPCoordinator.isScanningUnsupported()
    isUnsupported = true 
 } catch let error {
    throw error // or do nothing?
 }

 if isUnsupported {return nil }

如果您查看函数的 Swift 定义,我认为没有 return 值(即 void)。

您正在描述在 Objective-C 中产生错误的函数在 Swift 中被解释的标准方式。 Objective-C 中接受错误指针的方法和 return BOOL 被假定为无效并默认抛出 Swift。

这是因为在 Objective-C 中几乎总是这个意思。即 true 表示 "ran successfully",false 表示 "failed and I put the error in the pointer you supplied".

您的方法不符合正常的 Objective-C 约定,因此您可以尝试使用 NS_SWIFT_NOTHROW 宏在 [= 的声明中禁用 Swift 到抛出函数的转换19=].

这对我有用:

    if let _ = try? PPCoordinator.isScanningUnsupported() { return nil }