Swift 1.2 Nullability is Improving My Objective C Code

Swift 1.2 introduced ‘nullability’, a feature whereby you can annotate your Objective C headers and declare method parameters, propterties, and returned objects as ‘possibly nil’ or ‘never nil’ (a third edge case will be undiscussed here).

I support a library that might be used with earlier versions of Swift and/or Xcode, so need to use the annotation in a backward compatible fashion.

What I discovered is that the ‘pragma’s don’t generate any warnings so it would appear you can just add those:

#pragma clang assume_nonnull begin // start of interface
// interface
#pragma clang assume_nonnull end // end of interface

However, the ‘nullable’ and ‘non-nullable’ annotations cause older Xcodes errors, and files won’t compile. The workaround is to use this construct:

#if ! __has_feature(nullability)
#define nullable
#define nonnull
#endif

So the above is one way to deal with the mechanics of using this new feature. But what of the actual feature itself?

When I sat down and looked at my code, I realized that I was often returning nil for an array that could have returned objects, but no objects met the criteria. After all, we all know that ‘[array count]’ return 0 for a nil array and for an actual array with no objects, right?

But really, this is sloppy coding. In one case, I have a protocol method that can return an array of objects and an optional NSError – if success always return an array and no error, and if failure then no array and an error.

This now maps much better into Swift – I can use ‘if let’ to test for an array, if there process as a successful return, and in no array then use ‘!’ on the NSError as it must be there.

I spent an hour or two really thinking about what I was doing in the public facing interfaces, and tweaking them to be more Swift friendly, which also meant they are now more internally consistent and don’t seem so haphazard.

Advertisements