下面的 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 值 NO
或 nil
对象指针,
如记录在
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/