ios - 为什么 Swift Int 零在 objc 代码中读取为 nil?

标签 ios objective-c swift

我正在开发一个混合的 objc 和 swift 项目,我注意到当我从 Objc 读取这个值时,当我在 Swift 类中有一个值为 0 的 Int 属性时代码返回 nil

一个带有 ObjC 可见的整数属性的 Swift 类:

@objc
class SwiftInt: NSObject {

    @objc let testInt: Int = 0
}

现在当我在 Objc 代码中读取这个属性时,它说 testIntnil:

- (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/

相关文章:

ios - 如何使用 swift 从 launchOptions 获取自定义推送通知值?

ios - 单击 UIImageView 更改 ViewController

ios - UISearchBar 将半透明设置为 NO 不起作用

objective-c - 左侧标注图像未显示在 MKMapView 注释 View 中

objective-c - 处理 Objective C 中的无限循环

iphone - 这是什么意思 : NSString *string = NO ? @"aaa": @"bbb";

ios - dyld_shared_cache_extract_dylibs 在 iOS 13.1.3 上运行 6 秒以上失败

ios - 使用 CoreNFC 检测 ISO/IEC 14443(Mifare Ultralight 或 Classic)NFC 卡

ios - Swift - 一个屏幕到另一个屏幕

iOS Charts Swift 条形图超出视野