How to Make Compiler Assume `nullable` by Default

5.2k views Asked by At

Since Xcode 6.3, types in Objective-C can be marked with nullable or nonnull, here is Apple's blog post about this.

Problem is, when neither is specified, then the compiler imports the Objective-C code as implicitly unwrapped into Swift, e.g. NSView!. So when an object actually is nil, then it will crash when accessed from Swift. This does not produce a compiler error.

As this is extremely prone to fail, I'd like the compiler to assume everything from Objective-C by default as nullable, except when otherwise specified via nonnull, or the audited region macros NS_ASSUME_NONNULL_BEGIN / END. How can that be achieved?

3

There are 3 answers

0
fabb On BEST ANSWER

Seems like there is no way around adding nullability annotations in order to get rid of implicitly unwrapped optionals.

I wrote a script that finds all non-annotated headers which can also be added as a build phase, so no headers are overlooked.

3
CodeSmile On

Since the macro is defined as:

#define NS_ASSUME_NONNULL_BEGIN _Pragma("clang assume_nonnull begin")
#define NS_ASSUME_NONNULL_END   _Pragma("clang assume_nonnull end")

It may be worth trying to see if there's a corresponding assume_nullable macro.

#define XX_ASSUME_NULLABLE_BEGIN _Pragma("clang assume_nullable begin")
#define XX_ASSUME_NULLABLE_END   _Pragma("clang assume_nullable end")

I only did a quick test to check if this pragma fails compilation, which it didn't. But I haven't tested whether this produces the expected results in Swift.

1
Kraming On

Not exactly what you are looking for but from Xcode 7, you can turn on CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION in LLVM complier settings by passing -Wnullable-to-nonnull-conversion flag in complier flag. This will warn if there is a implicit conversion from nullable to non-nullable conversion.