Swift 2.2 上的可选绑定错误?

Optional binding bug on Swift 2.2?

if let mathematicalSymbol = sender.currentTitle {
    brain.performOperation(mathematicalSymbol)
}

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

Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

如该屏幕截图所示;

sender.currentTitle 是可选的。

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

If the optional value is nil, the conditional is false and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after let, which makes the unwrapped value available inside the block of code.

这是该摘录的示例代码;

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

如果您查看 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)
    }
}