【问题标题】:Optional binding bug on Swift 2.2?Swift 2.2 上的可选绑定错误?
【发布时间】:2016-08-01 17:31:23
【问题描述】:
if let mathematicalSymbol = sender.currentTitle {
    brain.performOperation(mathematicalSymbol)
}

上面的代码引入了下面的错误;

可选类型“字符串?”的值未拆封;你的意思是用 '!'还是“?”?

从这个屏幕截图中可以看出;

sender.currentTitle 是可选的。

这是 Apple 的“The Swift Programming Language (Swift 2.2)”的摘录,其示例代码就在其下方;

如果可选值为nil,则条件为false,代码 大括号中的被跳过。否则,可选值是 unwrapped 并且 分配给let 之后的常量,这使得展开值 在代码块中可用。

这是该摘录的示例代码;

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

因此,出于这些原因,我认为要么是我遗漏了什么,要么是我遇到了一个错误

我也在 Playground 上尝试过类似的东西,但没有收到类似的错误;

这是我的 Swift 版本;

Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.31)
Target: x86_64-apple-macosx10.9

【问题讨论】:

标签: swift xcode compiler-errors optional-binding


【解决方案1】:

如果您查看currentTitle,您会发现它很可能被推断为String??。例如,在 Xcode 中转到 currentTitle 并点击 esc 键以查看代码完成选项,您将看到它认为它是什么类型:

我怀疑您在将sender 定义为AnyObject 的方法中有这个,例如:

@IBAction func didTapButton(sender: AnyObject) {
    if let mathematicalSymbol = sender.currentTitle {
        brain.performOperation(mathematicalSymbol)
    }
}

但是如果你明确告诉它sender是什么类型,你可以避免这个错误,即:

@IBAction func didTapButton(sender: UIButton) {
    if let mathematicalSymbol = sender.currentTitle {
        brain.performOperation(mathematicalSymbol)
    }
}

或者

@IBAction func didTapButton(sender: AnyObject) {
    if let button = sender as? UIButton, let mathematicalSymbol = button.currentTitle {
        brain.performOperation(mathematicalSymbol)
    }
}

【讨论】:

  • if let mathematicalSymbol = (sender as? UIButton)?.currentTitle { 也可以。
  • 我觉得 Xcode 默认为 AnyObjectsender 类型很烦人。 AnyObject 很少有人会想要发件人,所以如果他们真的想要它,用户应该必须选择它,恕我直言。
  • 同意。当我拖放我的IBAction 连接时,我总是在下拉列表中选择特定类型,而不是接受AnyObject 默认值。我不喜欢 Objective-C 中的后一种行为,现在更糟了,太笨拙了。
  • @Rob,你说得对。这是我遇到的确切问题,在检查我的sender 的类型后,我注意到它是AnyObject,正如你所猜测的那样。我总是尝试更改它,但在这种情况下忘记了这样做,因此出现了这个错误。当我使用UIButton 时,它已解决。此外,检查UIButton 的类型如预期的那样显示为String? - 而String?? 则为AnyObject。苹果真的应该改变默认为AnyObject 的行为。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-06-09
  • 2017-01-28
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多