5

Does the Objective-C compiler actually warn you if it thinks that you may be passing nil to a parameter marked with _Nonnull?

Or is it merely a hint to whatever tool converts between Swift and Objective-C to better deal with Swift optionals?

4

1 回答 1

3

就其本身而言,只有在极其微不足道的情况下才会发出警告:当您传递nil给接受_Nonnull值的函数时。

NSObject* _Nonnull test(NSObject* _Nonnull) {
    test(nil);  // warning

    NSObject* _Nullable f = nil;
    test(f); // no warning (passing _Nullable to _Nonnull), only warn in static analysis

    NSObject* _Nonnull g = [[NSObject alloc] init];
    g = nil; // no warning (!) (assigning nil to _Nonnull)

    if (g != nil) {  // no warning (unnecessary '!= nil' comparison)
        test(g);
    }

    return nil; // no warning (returning nil to _Nonnull)
}

上面的代码在 Xcode 7 中编译时

(有一个-Wnullable-to-nonnull-conversion标志,但它似乎对上面的代码没有任何影响。)

如文档所述,这三个属性不会改变代码的行为:

…请注意,与声明属性不同nonnull,存在_Nonnull 并不意味着传递 null 是未定义的行为fetch可以自由地考虑 null 未定义的行为或(可能出于向后兼容的原因)防御性地处理 null

除了编译器之外,它还可以帮助静态分析器,但同样,clang 的静态分析器只会捕获它确定您将 a 分配给 a 的琐碎情况nil_Nonnulltest(f)上面的示例)。

_Nonnull尽管如此,将指针/标记_Nullable为仍然很有用

  1. 文件;
  2. 让 Swift 开发者更好地使用你的库;
  3. 如果您不添加这些注释,编译器将在各处发出警告
于 2016-05-12T05:57:06.567 回答