Why Swift Int zero is read nil in objc code?

Ist*_*van 2 objective-c ios swift

我正在研究objc和swift的混合项目,而且我注意到,当我Int从Objc代码读取此值时,当我在Swift类中有一个值为0 的属性时,它就会返回nil

一个带有整数属性的Swift类,可以从ObjC中看到它:

@objc
class SwiftInt: NSObject {

    @objc let testInt: Int = 0
}
Run Code Online (Sandbox Code Playgroud)

现在,当我在Objc代码中读取此属性时,它说的testIntnil

- (void)viewDidLoad {
    [super viewDidLoad];
    SwiftInt *swiftInt = [SwiftInt new];
    if (swiftInt.testInt == nil) {
        NSLog(@"This shouldn't be nil");
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我设置的其他数字不是0,则该值将正确返回,但对于0,它将返回nil。问题是,为什么nil在Objc中这Int是原始类型并且是非可选的?我正在使用Swift 4.2。

Man*_*ear 7

因为在Objective-C中nil定义为__DARWIN_NULL

#ifndef nil
# if __has_feature(cxx_nullptr)
#   define nil nullptr
# else
#   define nil __DARWIN_NULL
# endif
#endif
Run Code Online (Sandbox Code Playgroud)

定义(void *)0在Obj-C中

所以你的代码:

if (swiftInt.testInt == nil) { ... }
if (0 == nil) { ... }
if (0 == 0) { ... }
Run Code Online (Sandbox Code Playgroud)

总是如此

关于nilObj-C的好文章http://benford.me/blog/the-macro-behind-nil/