【问题标题】:Why doesn't this optional binding work as expected?为什么这个可选绑定不能按预期工作?
【发布时间】:2016-10-27 16:54:49
【问题描述】:

我正在将 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;

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

【问题讨论】:

  • 我刚试过,似乎正在使用 xcode 8 和 swift 3
  • 您能否提供完整的最小可验证示例代码,让我在自己的机器上重现该现象?
  • @matt 我会努力解决这个问题......与此同时,不确定它是否重要,但 propertyThatCouldBeNil 定义实际上是在包含 someOtherProperty 的类符合的 Objective-C 协议中。
  • 明白,但这还不足以让我猜测您的代码必须是什么。我不会坐在这里根据您的模糊提示尝试各种组合。提供细节你的工作。
  • 这是正确的芽。您可能想阅读我的书中关于此主题的部分:apeth.com/swiftBook/ch04.html#SECoptionalProtocol

标签: ios objective-c swift swift3 optional-binding


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 2015-06-09
    • 2017-02-23
    相关资源
    最近更新 更多