Learn Courses My Dashboard

Error-proofing an app in the wild

I really like the classes. Chris et al are very thorough and interesting. There’s a lot to learn…

As I said before, for most of my career, I’ve been a professional coder (I started before “coder” was a word; we called ourselves “programmers”) and I know that once an app enters the “wild” anything can go wrong. My specific question refers to this example from Databases M2 L4.

Notice this bug → let contentMap = doc[“contant”] as! [String:Any] ← I misspelled “content”. XCode returned “Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value”

“In the wild” a database could get broken resulting in a crash. Can someone point me to a reference on how to code to protect an app from something like this. I’m thinking that we can’t code to catch the error and fix the database, but we can code to catch the crash and to, at least, tell the user to call support.

The first thing you can do to catch errors in this situation is don’t force unwrap when you cast to to [String: Any]. Do something like this instead:

if let contentMap = doc["contant"] as? [String:Any] {
//work with the safely unwrapped Optional
}

Or:

guard let contentMap = doc["contant"] as? [String: Any] else {
//handle error condition
}

//work with the safely unwrapped Optional

to check your Optionals before you work with them and react accordingly if there’s an issue.

Force unwrapping in any situation where you are unsure if it is 100% safe to do so is asking for trouble. And even in that small percentage of cases it’s probably not that great an idea.

@roosterboy ‘s suggestions are all great.

Also avoid “stringly” typed things

Create something like an enum to define constants and use that enum then anytime you need to use that string. An enum is type safe and therefore you avoid ever mistyping any string

enum Docs {
   static let constant = “constant”
}

anytime you call it, it’d be Docs.constant

1 Like