Swift doesn't convert Objective-C NSError** to throws

后端 未结 2 1967
滥情空心
滥情空心 2020-12-08 20:32

I have some Objective-C legacy code, that declares method like

- (void)doSomethingWithArgument:(ArgType)argument error:(NSError **)error

As

2条回答
  •  甜味超标
    2020-12-08 21:31

    You need to make your method return a BOOL, to tell the runtime that an error should or should not be thrown. Also you should add __autoreleasing to the error parameter, to make sure ARC doesn't accidentally release the error before you have a chance to use it:

    - (BOOL)doSomethingWithArgument:(ArgType)argument error:(NSError * __autoreleasing *)error
    

    You can then call it from Swift like this:

    do {
        object.doSomethingWithArgument(someArgument)
    } catch let err as NSError {
        print("Error: \(err)")
    }
    

提交回复
热议问题