Search code examples
iosswifterror-handlingtype-safety

What To Do When a Guard Fails


My question basically is, what are some normal things to do when a guard fails? I am mostly asking in the context of an iOS application, where user interaction has requested something to happen and something must now be performed. Due to Swifts type-safety (which I love) we now may have optional values to take care of.

Here is an example:

guard let textField = (tableView.cellForRow(at: IndexPath(row: 0, section: 1)) as? TextInputTableViewCell)?.inputField else {
     print("Couldn't get the keyboard when a user clicked on done, method: accesoryKeyboardDone")
     return
}

Usually, I either log the failure and return or if it's vital that value is present, I'll fatalError out of the method. This seems like the wrong way to do this? Is there some way to fall back to a better case and still perform what the user has asked for? I like safely unwrapping values even though I need them to be there as force unwrapping makes me feel dirty and like I'm not doing something correctly. Is this something that I should be doing or is force unwrapping acceptable for these cases?

What are some ways that you approach handling optional values? I'm really just looking for opinions and tips on how other handle it.

Thank you!


Solution

  • The user should only be alerted for things that you expect to fail; for instance a network request that doesn't go through because they don't have internet. You don't have to alert the user for every single possible error; its often sufficient to either log it or just exit scope. Also you don't always need to pop up an alert box. See DZNEmptySet as an example.