我正在开发一个混合的 objc 和 swift 项目,我注意到当我从 Objc 读取这个值时,当我在 Swift 类中有一个值为 0 的 Int
属性时代码返回 nil
。
一个带有 ObjC 可见的整数属性的 Swift 类:
@objc
class SwiftInt: NSObject {
@objc let testInt: Int = 0
}
现在当我在 Objc 代码中读取这个属性时,它说 testInt
是 nil
:
- (void)viewDidLoad {
[super viewDidLoad];
SwiftInt *swiftInt = [SwiftInt new];
if (swiftInt.testInt == nil) {
NSLog(@"This shouldn't be nil");
}
}
如果我设置除 0 以外的任何其他数字,该值将正确返回,但对于 0,它返回 nil。问题是为什么 nil
在 Objc 中,而 Int
是原始类型并且它是非可选的?我正在使用 Swift 4.2。
最佳答案
因为在 Objective-C 中 nil
定义为 __DARWIN_NULL
:
#ifndef nil
# if __has_feature(cxx_nullptr)
# define nil nullptr
# else
# define nil __DARWIN_NULL
# endif
#endif
在 Obj-C 中定义为 (void *)0
所以你的代码:
if (swiftInt.testInt == nil) { ... }
if (0 == nil) { ... }
if (0 == 0) { ... }
永远正确
关于 Obj-C 中的 nil
的好文章 http://benford.me/blog/the-macro-behind-nil/
关于ios - 为什么 Swift Int 零在 objc 代码中读取为 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55278612/