Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the guard condition in the body of statement

Tags:

ios

swift

I'm making a url request in Swift and want to print a meaningful error including the response code should their be one. I'm attempting to do this in as few lines of code as possible. The error I'm getting in XCode is the following : Variable declared in 'guard' condition not usable in its body.

How can I perform the following without bloating the code to more lines, is it possible?

 //check to see if we got a valid response code
    guard let resCode = (response as? NSHTTPURLResponse)?.statusCode where resCode == 200 else {
        return NSError(domain: "Error with request", code: 1, userInfo: [NSLocalizedDescriptionKey: "Recieved the following status code: \(resCode)"])
    }

The error occurs with my attempting to use the variable resCode within the body of the guard statement.

like image 298
Jonathan Eustace Avatar asked Apr 27 '16 19:04

Jonathan Eustace


1 Answers

As the error states, you can't use a variable that you bound in the guard statement inside of the guard statement's body. The variable only gets bound in the case where the guard body is not entered. You also aren't differentiating between the cases where your response is nil and where your status code isn't 200.

You should break the statements into two different checks:

guard let httpResponse = response as? NSHTTPURLResponse else {
    return NSError(domain: "Error with request", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid response: \(response)"])
}

guard httpResponse.statusCode == 200 else {
    return NSError(domain: "Error with request", code: 1, userInfo: [NSLocalizedDescriptionKey: "Recieved the following status code: \(httpResponse.statusCode)"])
}

Don't try to minimize the number of lines of code at the expense of readability or correctness.

like image 189
dan Avatar answered Sep 20 '22 15:09

dan