Search code examples
swiftscopedo-catch

Best practice for accessing variables from a do-catch block


A standard do-catch block looks like this in Swift:

let jsonEncoder = JSONEncoder()
do {
  let file = try jsonEncoder.encode(pets)
} catch {
  return
}
// want to access file here

My question is what is the best practice for accessing the variable created inside the do-catch block? My instinct says to first create the variable outside the block as a unwrapped optional (let file: Data!) but it doesn't feel very elegant. Is there a better way to do this?


Solution

  • You can simply declare file outside the scope of the do-catch block and then access it after the the do-catch block. This works, because you are returning from the catch block, so you can never reach the print statement without file being initialised - it either gets a value from the do block or the function returns from the catch block, in which case the print is never executed.

    let jsonEncoder = JSONEncoder()
    let file: Data
    do {
        file = try jsonEncoder.encode(pets)
    } catch {
        return
    }
    // Do whatever you need with file
    print(file)