1

I am using the below code to download data from a server. According to Crashlytics, we see a crash occurred (EXC_BREAKPOINT) on the conditional evaluation (the 'if' statement). I suspect it is because the code unpacking the optional member "statusCode" - I am new to Swift (10 years doing Obj-C) - and I am not certain what the best, safest way is to unpack this variable without causing a crash.

Note that this app its using SwiftyJSON, though I do not think that is relevant.

    Alamofire.request(url).responseJSON { (response) in
        if (response.response?.statusCode)! >= 200 && (response.response?.statusCode)! < 300
1
  • Try if let or guard let statement to safely unwrap optionals. guard let alamResponse = response.renpose?.statuCode else {return}
    – akaakoz
    Nov 29, 2018 at 0:34

1 Answer 1

1
Alamofire.request(url).validate().responseJSON { response in
    switch response.result {
    case .success(let json):
        // do something with json
    case .failure(let error):
        // handle error
    }
}

The validate() method replaces your line checking the statusCode. It defaults to using acceptableStatusCodes which are 200..<300.

I think that's the best way to handle this specific case.

For more general cases, you should avoid force unwrapping. Unwrap the optional using guard or if let. The Swift docs explain that in detail.

1
  • I probably should have included more of the code - the next line after the response code check is a switch statement on the response.result. My assumption is the previous developer decided the switch on response.result was not catching everything, and added the IF statement on statusCode. Or, the previous developer didn't understand how response.result is determined, and added the statusCode check preemptively, and for no good reason. So, based on what I see from other devs who post examples, it does appear the statusCode check is unneeded. I will remove it. Thanks.
    – Jordan
    Nov 29, 2018 at 3:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.