ios - Swift doesn't convert Objective-C NSError** to throws -
i have objective-c legacy code, declares method like
- (void)dosomethingwithargument:(argtype)argument error:(nserror **)error
as written here https://developer.apple.com/library/ios/documentation/swift/conceptual/buildingcocoaapps/adoptingcocoadesignpatterns.html
swift automatically translates objective-c methods produce errors methods throw error according swift’s native error handling functionality.
but in project described methods called this:
object.dosomething(argument: argtype, error: nserrorpointer)
moreover, throws runtime exception when try use them like:
let errorptr = nserrorpointer() object.dosomething(argumentvalue, error: errorptr)
do need more convert objective-c "nserror **" methods swift "trows" methods?
only objective-c methods return bool
or (nullable) object translated throwing methods in swift.
the reason cocoa methods use return value no
or nil
indicate failure of method, , not set error object. documented in using , creating error objects:
important: success or failure indicated return value of method. although cocoa methods indirectly return error objects in cocoa error domain guaranteed return such objects if method indicates failure directly returning nil or no, should check return value nil or no before attempting nserror object.
for example, objective-c interface
@interface oclass : nsobject ns_assume_nonnull_begin -(void)dosomethingwithargument1:(int) x error:(nserror **)error; -(bool)dosomethingwithargument2:(int) x error:(nserror **)error; -(nsstring *)dosomethingwithargument3:(int) x error:(nserror **)error; -(nsstring * _nullable)dosomethingwithargument4:(int) x error:(nserror **)error; ns_assume_nonnull_end @end
is mapped swift as
public class oclass : nsobject { public func dosomethingwithargument1(x: int32, error: nserrorpointer) public func dosomethingwithargument2(x: int32) throws public func dosomethingwithargument3(x: int32, error: nserrorpointer) -> string public func dosomethingwithargument4(x: int32) throws -> string }
if can change interface of method should add boolean return value indicate success or failure.
otherwise call swift as
var error : nserror? object.dosomethingwithargument(argumentvalue, error: &error) if let theerror = error { print(theerror) }
remark: at
i found clang has attribute forces function throw error in swift:
-(void)dosomethingwithargument5:(int) x error:(nserror **)error __attribute__((swift_error(nonnull_error)));
is mapped swift as
public func dosomethingwithargument5(x: int32) throws
and seems work "as expected". however, not find official documentation attribute, might not idea rely on it.
wiki
Comments
Post a Comment