Tuesday, March 24, 2020 [Tweets] [Favorites]

Making Swift Properties Overridable Only in Debug Builds

John Sundell:

Occasionally, we might want to override certain properties in order to facilitate testing, to be able to work on a new feature, or to debug a problem.

[…]

Here’s a way to mitigate that problem, using Swift’s new property wrappers feature in combination with the DEBUG compiler flag. By creating a DebugOverridable property wrapper, we can enforce that the properties that we wish to override during testing and development are not actually overridden within any of our code that we’re shipping to production[…]

This is a neat trick, though unfortunately property wrappers don’t work with @NSManaged. What I have been doing is having my tests use underscored versions of the properties. These are a declared in an extension, which is conditionally compiled only when the TEST flag is set.

I’d still like to see Swift’s access controls reworked to make testing easier. @testable import doesn’t really do the job because it only works for symbols that are already visible at the package level. So you can only use private for stuff that will never be used from tests.

Previously:

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment