Search code examples
swift

How to avoid multiple do try catch statements in Swift


I was creating some code and I find a problem that can escalate quickly on my do try catch.

This is my code in Swift:

    do {
        let sendResponseModel = try JSONDecoder().decode(SendResponseModel.self, from: data)
        redirectUserToScreen1(sendResponseModel)
    } catch {
        dprint("first catch")
        do {
            let sendAnotherResponseModel = try JSONDecoder().decode(SendAnotherResponseModel.self, from: data)
            redirectUserToScreen2(sendAnotherResponseModel)
        }
        catch {
            dprint("second catch")
        }
    }

I got a http json response that becomes Data , but it comes from different sources in this case. I will need to create more "try JSONDecoder().decode".

Is that possible to create some type of code to not create a nested "do try catch" statements?


Solution

  • I use the @Sweeper idea to create the code below

        if let sendPixResponseModel: SendPixResponseModel = try? JSONDecoder().decode(SendPixResponseModel.self, from: data) 
        {
            dprint("sendPixResponseModel: \(sendPixResponseModel)")
            GetBancoByISPB(sendPixResponseModel.recebedor.ispb)
        }
        else if let SendPixBranchAgencyAndAccountResponseModel: SendPixBranchAgencyAndAccountResponseModel = try?  JSONDecoder().decode(SendPixBranchAgencyAndAccountResponseModel.self, from: data)
        {
            dprint("SendPixBranchAgencyAndAccountResponseModel: \(SendPixBranchAgencyAndAccountResponseModel)")
            
            ComprovanteStaticValues.setDataOnComprovante(SendPixBranchAgencyAndAccountResponseModel)
            dprint("SendPixBranchAgencyAndAccountResponseModel: \(SendPixBranchAgencyAndAccountResponseModel)")
        }