【发布时间】:2019-03-21 10:42:07
【问题描述】:
我正在处理一个混合的 objc 和 swift 项目,我注意到当我在 Swift 类中有一个值为 0 的 Int 属性时,当我从 Objc 代码中读取此值时,它会返回 @987654322 @。
一个具有整数属性的 Swift 类,在 ObjC 中可见:
@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。问题是当Int 是原始类型并且它是非可选的时,为什么这个nil 在Objc 中?我正在使用 Swift 4.2。
【问题讨论】:
-
在 (Objective-)C 中,可以将整数与指针进行比较。
if (swiftInt.testInt == nil)等价于if (swiftInt.testInt == 0)– 应该有一个警告 "Comparison between pointer and integer ('int' and 'void *')" 虽然 -
您是只对
nil感兴趣还是对NULL、Nil和NSNull感兴趣? -
ObjC(具有Clegacy)根本无法区分nil和0(还有NO/false,swiftInt.testInt == NO或!swiftInt.testInt也可以也)。
标签: ios objective-c swift