Rikh Rikh - 11 months ago 76
iOS Question

Generate your own Error code in swift 3

What I am trying to achieve is perform a

request in swift 3. I am performing this action in a separate function (so as not to write the code separately for GET and POST) and returning the
and handling the success and failure in closures. Sort of like this-

let task = URLSession.shared.dataTask(with: request) { (data, uRLResponse, responseError) in

DispatchQueue.main.async {

var httpResponse = uRLResponse as! HTTPURLResponse

if responseError != nil && httpResponse.statusCode == 200{



if(responseError == nil){
//Trying to achieve something like below 2 lines
//Following line throws an error soo its not possible
//var errorTemp = Error(domain:"", code:httpResponse.statusCode, userInfo:nil)




I do not wish to handle the error condition in this function and wish to generate an error using the response code and return this Error to handle it wherever this function is called from.
Can anybody tell me how to go about this? Or is this not the "Swift" way to go about handling such situations?

Answer Source

In your case, the error is that you're trying to generate an Error instance. Error in Swift 3 is a protocol that can be used to define a custom error. This feature is especially for pure Swift applications to run on different OS.

In iOS development the NSError class is still available and it conforms to Error protocol.

So, if your purpose is only to propagate this error code, you can easily replace

var errorTemp = Error(domain:"", code:httpResponse.statusCode, userInfo:nil)


var errorTemp = NSError(domain:"", code:httpResponse.statusCode, userInfo:nil)

Otherwise check the Sandeep Bhandari answer regarding how to create a custom error type