0

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?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Carl
  • 683
  • 5
  • 18

1 Answers1

1

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)
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116