if let mathematicalSymbol = sender.currentTitle {
brain.performOperation(mathematicalSymbol)
}
上面的代码介绍了以下错误;
可选类型'String?'的值没有打开;你的意思是用吗? '!'还是'?'?
从这个屏幕截图中可以看出;
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
答案 0 :(得分:3)
如果您查看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)
}
}