ios - 如何编写可以在 Objective C 中使用的带有 throws 语句和返回值的 swift 3 方法?

标签 ios objective-c swift swift3

下面的 Swift 3 方法被翻译成 Objective C,如下所示:

func doSomething(param: String) throws // Swift 3

- (BOOL)doSomething:(NSString * _Nonnull)param error:(NSError * _Nullable * _Nullable)error; // Translated Objective C

那么,如何写一个既有抛出又有返回类型的方法呢?

func doSomething(param: String) throws -> Int // Swift 3

// Error: Never translated into Objective C

我知道流程不应该由 NSError 对象处理。它只包含有关错误的信息。这就是为什么有一个 BOOL 返回类型让我们知道调用成功没有任何问题。

那么如何处理同时具有 throws 语句和返回类型的方法?有没有标准的方法来处理这个问题?

提前谢谢你。

最佳答案

在 Objective-C 中报告成功或失败的标准方式是 返回 bool 值 NOnil 对象指针, 如记录在 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.

所以你可以返回一个对象的实例

func doSomething(param: String) throws -> NSNumber

翻译成

- (NSNumber * _Nullable)doSomethingWithParam:(NSString * _Nonnull)param error:(NSError * _Nullable * _Nullable)error;

如果抛出错误则返回nil,或者返回一个 bool 值和 通过引用传回其他值

func doSomething(param: String, value: UnsafeMutablePointer<Int>) throws

映射到

- (BOOL)doSomethingWithParam:(NSString * _Nonnull)param value:(NSInteger * _Nonnull)value error:(NSError * _Nullable * _Nullable)error;

关于ios - 如何编写可以在 Objective C 中使用的带有 throws 语句和返回值的 swift 3 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42570642/

相关文章:

ios - 如何使用alertcontroller添加警报消息?

iOS:使用 IBOutlets 的 ARC 强引用或弱引用(用于自定义 UITableviewCell)

ios - 原因 : '-[_UIFullscreenPresentationController adaptivePresentationController]:

ios - 将html文件从swift 3中的本地自定义文件夹加载到WebView

iphone - 是否可以在不打开特定 View 的情况下拍摄屏幕截图?

iphone - 如何让 UITextField 响应 UITextFieldDelegate?

objective-c - 使用 NSImage 进行 Cocoa 图像压缩

java - android中字符串的int比较

ios - 按特定顺序对自定义对象进行排序

ios - 不使用 SearchBar 过滤 UITableView