19

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?

fabb
  • 11,660
  • 13
  • 67
  • 111

3 Answers3

0

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.

Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
Kraming
  • 217
  • 3
  • 8
0

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.

fabb
  • 11,660
  • 13
  • 67
  • 111
-2

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.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
  • 1
    Yeah, there doesn't seem to be an equivalent preprocessor macro for that: http://clang.llvm.org/doxygen/classclang_1_1Preprocessor.html – Ben Flynn Oct 14 '15 at 18:01
  • A variable marked with `nonnull` is safe and `nullable` one is not, so `nullable` mark should be specified every time. – DawnSong Jun 15 '18 at 08:20
  • Nice try... pity it doesn't work. I agree it is much needed, and in real-world programming, there are many structures that accumulate Lot's of nullable properties (things you may/may-not find in a parsed input (say JSON, XML, Plist etc.) and it makes perfect sense to NS_ASSUME_NULLABLE_BEGIN/END on groups of these. It has nothing to do with "safety" when your world is ObjC and when you write daemons and frameworks - that are NOT even available from Swift. – Motti Shneor Nov 03 '21 at 08:47