Hacker News new | ask | show | jobs
by krzat 2460 days ago
Guard with assertionFailure and explanation for why it was used is much easier to notice and understand than !.
1 comments

You know, I used to think that but I've come to realize that I often just ended up writing messages that were not useful. For example, here is some code that I wrote a while back:

  guard let data = notification.userInfo?["updatedItem"] as? Data else {
      assertionFailure("Could not retrieve updated item")
      return false
  }
I am really being helpful here? If I see a crash on this line:

  let data = notification.userInfo?["updatedItem"] as! Data
I get essentially the same information, except it's done in a less verbose and easier-to-discover way. Whereas the first one is like adding this kind of useless comment:

  let x = 5 // Assign 5 to x
Two problems I see:

1. ! used here is hard to spot, it's just few pixels of difference from ?.

2. assertionFailure is not the same as force unwrap, because it crashes only in debug mode. Ideally you would log it with some analytics so developers know if problem occured, but doing nothing is usually better than crashing the app.