我是 Swift 的新手,我开始探索一些与 Objective-C 桥接的功能。
目前我有一个带有 NSError
引用的方法是:
- (BOOL) verifyPersonalizationWithError:(NSError **) error NS_REFINED_FOR_SWIFT;
现在我可以访问 Swift 中的方法进行一些改进,但返回值丢失了。 Swift 生成的方法是:
open func __verifyPersonalization() throws
用 do catch 正确处理了错误,但返回值似乎丢失了。
我的 NS_REFINED_FOR_SWIFT 宏有什么遗漏吗?
最佳答案
这与 NS_REFINED_FOR_SWIFT
宏无关。 Objective-C
方法
- (BOOL) verifyPersonalizationWithError:(NSError **) error;
导入到 Swift 作为
open func verifyPersonalization() throws
NS_REFINED_FOR_SWIFT
宏的唯一作用是在前面加上
Swift 方法名称的下划线
open func __verifyPersonalization() throws
允许在扩展中提供精化的 Swift 接口(interface),同时保持原始实现可用于从精化接口(interface)调用 (参见 Swift and Objective-C in the Same Project 中的“精炼 Objective-C 声明”)。
Swift 导入器假定 Objective-C 方法的 bool 返回值表示成功或 失败,这是常见的 Cocoa 模式 如 Using and Creating Error Objects 中所述:
Important: Success or failure is indicated by the return value of the method. Although Cocoa methods that indirectly return error objects in the Cocoa error domain are guaranteed to return such objects if the method indicates failure by directly returning nil or NO, you should always check that the return value is nil or NO before attempting to do anything with the NSError object.
Objective-C 中的典型用法是
NSError *error;
if ([self verifyPersonalizationWithError:&error]) {
NSLog(@"success");
} else {
NSLog(@"failed: %@", error.localizedDescription);
}
Swift 方法在失败时抛出错误,所以没有必要 对于 bool 返回值:
do {
try verifyPersonalization()
print("success")
} catch {
print("failed:", error.localizedDescription)
}
如果 Objective-C 方法真的通过离开来指示失败
error 参数中的非空错误(而不是返回 false
,这是通常的 Cocoa 模式)然后你可以指出
通过添加属性:
- (BOOL) verifyPersonalizationWithError:(NSError **) error
__attribute__((swift_error(nonnull_error)));
导入到 Swift 作为
open func verifyPersonalization() throws -> Bool
swift_error
属性记录在 https://github.com/apple/swift-clang/blob/383859a9c4b964af3d127b5cc8abd0a8f11dd164/include/clang/Basic/AttrDocs.td#L1800-L1819
关于objective-c - NS_REFINED_FOR_SWIFT 和返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45565960/