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

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

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

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

在此处输入图像描述

sender.currentTitle是可选的。

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

如果可选值是nil,则条件是false并且大括号中的代码被跳过。否则,可选值被解包并分配给常量 after 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
4

1 回答 1

3

如果你看一下currentTitle,你会发现它很可能是推断出来的String??。例如,currentTitle在 Xcode 中按一下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)
    }
}
于 2016-08-01T17:40:48.900 回答