-1

我正在将 Swift 引入一个 Objective-C 应用程序。

我有一个 UIViewController 子类,如果某个属性为零,我想在其中隐藏一个按钮。我的 Swift 代码如下所示,使用可选绑定:

if let optionalVar = modelObject.propertyThatCouldBeNil {
   button.setTitle(...)
} else {
   button.hidden = true
}

我的希望是当 propertyThatCouldBeNil 为 nil 时,if 不满足并且控制将继续到 else。但事实并非如此。事实上,如果我设置一个断点,我看到的是......

(lldb) po optionalVar
nil
(lldb) po modelObject.propertyThatCouldBeNil
▿ Optional<Optional<String>>
  - some : nil

后一个是什么让我有点绊倒。我认为它应该是可选的,而不是嵌套的,对吗?

更多信息...

由于我在整个此类中使用 modelObject,为方便起见,它被定义为隐式展开的可选...

var modelObject : ModelObjectClass!

ModelObjectClass 实际上是一个Objective-C 类,并且属性是只读的并声明为...

@property (readonly, nullable) NSString *propertyThatCouldBeNil;

在它的实现中,它实际上充当了另一种现成属性的代理...

- (NSString*) propertyThatCouldBeNil {
   return self.someOtherProperty;
}

而且 someOtherProperty 也可以为空......

@property (nullable, nonatomic, retain) NSString *someOtherProperty;

关于为什么可选绑定没有按我预期工作的任何见解?

4

1 回答 1

1

似乎和我一起工作

@interface ModelObjectClass : NSObject
    @property (readonly, nullable) NSString *propertyThatCouldBeNil;
    @property (nullable, nonatomic, retain) NSString *someOtherProperty;
    - (nullable NSString*) propertyThatCouldBeNil;
@end

@implementation ModelObjectClass
    - (nullable NSString*) propertyThatCouldBeNil {
        return self.someOtherProperty;
    }
@end

于 2016-10-27T17:45:18.023 回答