Skip to content

Instantly share code, notes, and snippets.

@jessesquires
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessesquires/e43298a91157d19b90d7 to your computer and use it in GitHub Desktop.
Save jessesquires/e43298a91157d19b90d7 to your computer and use it in GitHub Desktop.
Avoid using var with Swift try/catch?
var results = [MyModel]() // must use var :(
do {
results = try fetch(request: request, inContext: context)
}
catch {
print("Fetch error: \(error)")
}
// use results
print("Results = \(results)")
@jessesquires
Copy link
Author

Revision:
This is slightly better.

let results2: [MyModel]
do {
    results2 = try fetch(request: request, inContext: stack.managedObjectContext)
} catch {
    print("Error = \(error)")
    // This is awkward, but better than var
    results2 = [MyModel]()
}

print("Results = \(results2)")

@harlanhaskins
Copy link

I would probably use an optional here, or bail out of this scope entirely.

let results2: [MyModel]?
do {
    results2 = try fetch(request: request, inContext: stack.managedObjectContext)
} catch {
    print("Error = \(error)")
    // Less awkward, and still have to handle absence.
    results2 = nil
}

print("Results = \(results2)")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment