Swift2.0: How to get both return value and error using try catch

I have a function in Objective-C. This function always returns a value, an event if an error occurs:

-(NSString *)test:(NSError **)error;

I override it in Swift1 as follows, so that I can still get the value and error at the same time.

override func test(error: NSErrorPointer) -> String {
    var error: NSError?
    let result = super.test(&error)
    ...
}

But now in swift2 I can only redefine the function, for example

override func test() throws -> String {

} 

In this case, how to get the value and error at the same time?

I do this because I need to override the function in AFNetworking. Both return value and error are required.

- (id)responseObjectForResponse:(NSURLResponse *)response
                           data:(NSData *)data
                          error:(NSError *__autoreleasing *)error;    
+4
source share
2 answers

, , , Swift, .

AFNetworking Swift AlamoFire. Swift, AFNetworking. :

https://github.com/Alamofire/Alamofire

0

, BOOL. true, false .

Swift 2 do, try catch. NSError.

:

do {
  try something()
  // continue if something() returned true otherwise -> catch
} catch let error as NSError {
  print(error.localizedDescription)
}

AFNetworking - , NSError JSON:

override func responseObjectForResponse(response: NSURLResponse!, data: NSData!) throws -> AnyObject {
  do {
    try self.validateResponse(response as! NSHTTPURLResponse, data: data)
  } catch let error as NSError {
    let json = JSON(data: data) // i'm using SwiftyJSON : https://github.com/SwiftyJSON/SwiftyJSON
    if let errorMessage = json["error"].string {
      var userInfo = error.userInfo
      userInfo[NSLocalizedDescriptionKey] = errorMessage
      throw NSError(domain: error.domain, code: error.code, userInfo: userInfo)
    }
  }

  return try super.responseObjectForResponse(response, data: data)
}

, , Swift 2:)

0

Source: https://habr.com/ru/post/1607724/


All Articles