As Objective-C & Swift developers, we have to be a bit more concerned about nullability than our friends that work in dynamically typed languages. In the Swift community, we generally avoid bangs ( ! ) wherever possible — allowed only in special circumstances like cell dequeueing:

Why have we accepted this as okay in the community? The need to crash the application here is understandable: we’re missing a view in our application, and by all means this should be a fatal error, but the usage of ! is visually jarring, and throws a SwiftLint (or Tailor) warning. In many projects — especially, those that use a linter like SwiftLint or Tailor — we avoid this by guard ing and calling fatalError :

This is awesome for getting an explicit error out of the compiler, for killing the SwiftLint warning generated by the use of a bang, and for avoiding the force unwrap while still initiating a crash if needed. However, it’s hampered by two issues:

Manually writing an error on every potential failure point is tedious, and it’s easy for developers to do so.

Passing in a string identifier to dequeue a cell, header, or footer is error prone and can lead to deviations from the convention of matching identifiers to class names.

Let’s explore a better way.

ReusableViews is a library, available through CocoaPods, that takes Guille Gonzalez’ concept of cleanly and safely dequeueing UITableViewCell s to its logical conclusion: allowing idiomatic reuse and registration of all dequeue-able types, as well as clear instantiation of view controllers from storyboards.

At its core, ReusableViews is a syntactic sugar library. But in practice, it feels like part of Apple’s API. It allows you to express which class you’re trying to instantiate by passing in the type instead of a string identifier. When something goes wrong through its usage, you get a descriptive error telling you what went wrong, instead of EXC_BAD_ACCESS . And finally, because it relies on classes having identifiers that match their class name, it allows your team to follow an easy convention.

Showcased above, you can use the as syntax to instantiate an object, or you can declare its type as you instantiate it — you can use the syntax that your team prefers. And, this isn’t limited to programmatic views or storyboard-backed views — this works for nib-based views as well, provided that they inherit from NibLoadableView .

And, perhaps most importantly, when using this library, there is no longer any reason to use a force unwrap.

Contributing and Installing

ReusableViews is available on GitHub, production-ready, documented, well-tested, and open to new contributors.