25

I have gotten into a pretty good habit of declaring and using constant strings for things like NSNotification names. I declare them like so:

extern NSString * const ABCAwesomeThingHappenedNotification;

With the introduction of Xcode 6.3 and Swift 1.2, I'm going back and auditing Objective-C classes that interop with Swift using the new nonnull, nullable, and null_unspecified qualifiers.

When adding the qualifiers to a header that also has externally visible static strings, I receive the following warning:

warning: pointer is missing a nullability type specifier (__nonnull or __nullable)

Hmm. That's confusing / interesting. Can someone explain the reasoning behind this message? When using ABCAwesomeThingHappenedNotification in Swift, it never suggests that it's an optional String or implicitly unwrapped String.

edelaney05
  • 6,822
  • 6
  • 41
  • 65
  • 1
    Different question, but may also be interesting in this context: [Swift 1.2 optional external variable?](http://stackoverflow.com/questions/29612639/swift-1-2-optional-external-variable). – Martin R Apr 14 '15 at 16:51
  • Related: [How to create class methods that conform to a protocol shared between Swift and Objective-C?](http://stackoverflow.com/questions/29399871/how-to-create-class-methods-that-conform-to-a-protocol-shared-between-swift-and) (but this isn't a duplicate) – nhgrif May 18 '15 at 00:27
  • April, 2018. Still need to declare the __nonnull for extern * to avoid the error. – lal Apr 15 '18 at 21:40

2 Answers2

34

I agree that having this specifier shouldn't be required but here is syntax

extern NSString * const MyConstant;

extern NSString * __nonnull  const MyConstant;
Josip B.
  • 2,434
  • 1
  • 25
  • 30
7

In your implementation, you could define:

NSString * const ABCAwesomeThingHappenedNotification = @"ABCAwesomeThingHappenedNotification";

in which case the pointer is clearly nonnull. However, this is also valid:

NSString * const ABCAwesomeThingHappenedNotification = nil;

which must be considered nullable because the pointer is always a null pointer.

(The explicit initialisation to nil is redundant since this happens implicitly if no initial value is provided, but clarifies this example.)

Douglas Hill
  • 1,537
  • 10
  • 14