Objective-C 可空性:限定常量字符串
Objective-C Nullability: Qualifying Constant Strings
我已经养成了一个很好的习惯,即为 NSNotification
名称之类的东西声明和使用常量字符串。我这样声明它们:
extern NSString * const ABCAwesomeThingHappenedNotification;
随着 Xcode 6.3 和 Swift 1.2 的引入,我将回过头来审核 Objective-C 类 与 Swift 的互操作,使用新的 nonnull
、nullable
和 null_unspecified
限定符。
将限定符添加到也具有外部可见静态字符串的 header 时,我收到以下警告:
warning: pointer is missing a nullability type specifier (__nonnull or __nullable)
嗯。这令人困惑/有趣。有人可以解释此消息背后的原因吗?在 Swift 中使用 ABCAwesomeThingHappenedNotification
时,它从不暗示它是一个可选的字符串或隐式解包的字符串。
在您的实施中,您可以定义:
NSString * const ABCAwesomeThingHappenedNotification = @"ABCAwesomeThingHappenedNotification";
在这种情况下指针显然是nonnull
。然而,这也是有效的:
NSString * const ABCAwesomeThingHappenedNotification = nil;
必须考虑nullable
,因为指针始终是空指针。
(nil
的显式初始化是多余的,因为如果没有提供初始值,这会隐式发生,但澄清了这个例子。)
我同意不需要这个说明符,但这是语法
extern NSString * const MyConstant;
extern NSString * __nonnull const MyConstant;
我已经养成了一个很好的习惯,即为 NSNotification
名称之类的东西声明和使用常量字符串。我这样声明它们:
extern NSString * const ABCAwesomeThingHappenedNotification;
随着 Xcode 6.3 和 Swift 1.2 的引入,我将回过头来审核 Objective-C 类 与 Swift 的互操作,使用新的 nonnull
、nullable
和 null_unspecified
限定符。
将限定符添加到也具有外部可见静态字符串的 header 时,我收到以下警告:
warning: pointer is missing a nullability type specifier (__nonnull or __nullable)
嗯。这令人困惑/有趣。有人可以解释此消息背后的原因吗?在 Swift 中使用 ABCAwesomeThingHappenedNotification
时,它从不暗示它是一个可选的字符串或隐式解包的字符串。
在您的实施中,您可以定义:
NSString * const ABCAwesomeThingHappenedNotification = @"ABCAwesomeThingHappenedNotification";
在这种情况下指针显然是nonnull
。然而,这也是有效的:
NSString * const ABCAwesomeThingHappenedNotification = nil;
必须考虑nullable
,因为指针始终是空指针。
(nil
的显式初始化是多余的,因为如果没有提供初始值,这会隐式发生,但澄清了这个例子。)
我同意不需要这个说明符,但这是语法
extern NSString * const MyConstant;
extern NSString * __nonnull const MyConstant;