Recently I turned on CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION in Xcode and I am overwhelmed with nullability related warnings in my Objective-C code. The one warning type that is most prevalent is Implicit conversion from nullable pointer 'TypeA * _Nullable' to non-nullable pointer type 'TypeA * _Nonnull'.
I started my attempt to remove with these warnings by creating a local of the same type in a method as described here. https://www.mail-archive.com/xcode-users%40lists.apple.com/msg02260.html This article says by first using a local, that object is of attribute unspecified nullable, so it can be used as legit parameter to the methods expecting nonnull.
But I feel this is a cop out move and really not solving the issue in any beneficial way.
Has anyone gone through this exercise already? I would be grateful if you can share a strategy that you took.
Actually, I have messed around with that topic for a little bit. I wanted to improve nullability situation in a somewhat big project (make it more 'swiftier'). Here is what I found.
Firstly, you should turn on
CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION(-Wnullable-to-nonnull-conversion)Secondly, about
This smells bad, and I created a macro called
NONNUL_CAST(). Here is example how to implement it:Here you can see hacky
__typeof(*(__var))* _Nonnull)__var, but it is not so bad. If__varis of typeA* _Nullablewe dereference__var, so it's type now justA, after we make reference again, but_Nonnull, and get nonnull__varas answer. Of course we assert to, in case something goes wrong.Thirdly, you must specify nullabilty on every local variable, and you should put all your code in
NS_ASSUME_NONNULL_BEGIN/END, like this:You put there EVERY LINE (except imports) of your code, in
.hand.mfiles. That will assume that all your arguments of methods, return types and properties are nonnull. If you want to make it nullable, put nullable there.So, all done, now what? Here is example of typical usage:
Now you have more robust nullability situation. May be it is not looking nicely, but it is objective-c, so nothing to complain about.
UPDATE
Macro that works with block types (also probably with function types):