NickCE NickCE - 1 year ago 193
Swift Question

Nullability annotation warnings after NS_ASSUME_NONNULL_END

I was working on adding some nullability annotation to part of a header file, and I wanted the block to assume non-null, but pretty much every method afterwards was giving warning saying that I needed to add nullability annotations.

Example code for this below:

- (void)testMethodWithParameter:(NSString *)par otherParameter:(NSString *)otherPar;

- (void)methodThatShouldntNeedAnnotationWithText:(NSString *)txt;
//Warning: Pointer is missing a nullability type specifier (_Nonnull, _Nullable, or _Null_unspecified)

Am I understanding these Macros incorrectly? I thought it would contain the part that was said to be audited within the BEGIN/END block, but everything outside would still be

Is this working as intended, or is there something I have to do to make this work the way I thought?

Answer Source

NS_ASSUME_NONNULL_BEGIN makes any parameter to be assumed as a non null variable, therefore:

- (void)testMethodWithParameter:(NSString *)par otherParameter:(NSString *)otherPar;

is converted to:

- (void)testMethodWithParameter:(nonnull NSString *)par otherParameter:(nonnull NSString *)otherPar;

So, the absence of NS_ASSUME_NONNULL_BEGIN doesn't mean that every parameter is assumed to be nullable nor unspecified, you still have to define it. So, for the other method you have to specify what you want, if you want the text could be nullable then add the keyword to the parameter like this:

- (void)methodThatShouldntNeedAnnotationWithText:(nullable NSString *)txt;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download