Skip to content

Category: Swift

When is a Bool not a Bool?

This is a silly question — or rather, it should be a silly question — but it’s going to bite you sometimes when you integrate Objective-C and Swift code together (*cough* UIKit).

You will try to use what you think is a Bool from an Objective-C API, and suddenly you’re getting this compile error:

Cannot convert value of type ‘ObjCBool’ to expected argument type ‘Bool’

This is a Boolean value; why can’t I use this @($^ thing as a Bool?

Normally the standard types play nice between Objective-C and Swift. But Bools are an unusual case that require a non-obvious solution.

Force unwrapping is not just “not Swift-like.” It’s wrong.

Swift comes with a number of features that help developers write correct bug-free programs: optionals, safe casting, and built-in error handling. But for every one of these, there is an escape hatch: !, the force unwrapping operator.

You may know another developer or team member who plays a little fast and loose with force unwrapping. Or you don’t feel like doing the additional boilerplate to unwrap an optional, so you do it when “nobody’s looking.”

You may not have a good argument for why safe unwrapping is good and force unwrapping is bad, other than that the Swift documentation says so, or “that’s how it’s done.”

The reason behind safe unwrapping comes from a long history of languages that didn’t provide strong safeties such as these. This often resulted in trying to interpret random memory locations as objects, resulting in crashes at best, hard to debug app behavior at worst. Not using all of Swift’s safety mechanisms at your disposal is not just not Swift-like, it is bad programming.