
最近用 Xcode 6.3 寫代碼,凡是涉及對象的地方經常會冒出這樣一條編譯器警告:
Pointer is missing a nullability type specifier (__nonnull or __nullable)
查了一下才發現,這是 Xcode 6.3 引入的新特性:nullability annotations(空值註解)。
Swift 中用 ? 和 ! 明確區分 optional 與 non-optional,例如 view? 和 view!。Objective-C 沒有這層區分:一個 view 既可以為 nil,也可以不為 nil,全憑約定。
於是 Swift 與 Objective-C 混編時就出現了尷尬:Swift 編譯器無從判斷某個 Objective-C 對象到底能不能為空,只能隱式地把所有 Objective-C 對象都當作 non-optional 處理,埋下運行期崩潰的隱患。
蘋果的解法就是兩個新的類型註解:__nullable 與 __nonnull。顧名思義,前者表示對象可以是 NULL/nil,後者表示不應為空;一旦違反約定,編譯器就會给出警告。
@interface TestNullabilityClass ()
@property (nonatomic, copy) NSArray * items;
- (id)itemWithName:(NSString * __nonnull)name;
@end
@implementation TestNullabilityClass
...
- (void)testNullability {
[self itemWithName:nil]; // 編譯器警告:Null passed to a callee that requires a non-null argument
}
- (id)itemWithName:(NSString * __nonnull)name {
return nil;
}
@end注意這只是警告,程式依然能編譯通過並運行。
凡是能寫 const 的位置,基本都能用 __nullable 和 __nonnull,但它們只作用於指針類型。在方法聲明裡,還可以使用不帶下劃線的寫法:
- (nullable id)itemWithName:(NSString * nonnull)name
屬性聲明也新增了對應的特性,前面的 items 可以寫成:
@property (nonatomic, copy, nonnull) NSArray * items;
或者:
@property (nonatomic, copy) NSArray * __nonnull items;
推薦前者,聲明讀起來更清爽。
如果每個屬性、每個方法都手寫 nonnull/nullable,實在繁瑣。蘋果因此提供了兩個宏:NS_ASSUME_NONNULL_BEGIN 與 NS_ASSUME_NONNULL_END。這對宏之間的所有簡單指針都預設為 nonnull,你只需要標注那些真的可空的:
NS_ASSUME_NONNULL_BEGIN @interface TestNullabilityClass () @property (nonatomic, copy) NSArray * items; - (id)itemWithName:(nullable NSString *)name; @end NS_ASSUME_NONNULL_END
上例中,items 預設 nonnull,itemWithName: 的返回值也是 nonnull,只有參數被顯式標成了 nullable。
不過出於安全考慮,蘋果規定了幾條例外:
既然是 6.3 才有的語法,老代碼自然要考慮。蘋果在這點上做得相當體貼:
與其把 nonnull/nullable 看成語法糖,不如把它們和斷言、異常放在一起理解——它們約束的都是同一件事:違反約定屬於程序員的錯誤。尤其是返回值,完全在我們掌控之中:聲明為 nonnull 就不該返回 nil,除非是為了向後兼容。
參考:Nullability and Objective-C