简体   繁体   English

Swift 2.2上的可选绑定错误?

[英]Optional binding bug on Swift 2.2?

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

The code above introduces the error below; 上面的代码引入了以下错误;

Value of optional type 'String?' 可选类型'String?'的值 not unwrapped; 不展开 did you mean to use '!' 你是说用'!' or '?'? 要么 '?'?

As can be seen in this screen shot; 从该屏幕截图可以看出;

在此处输入图片说明

sender.currentTitle is an optional. sender.currentTitle是可选的。

Here is an excerpt from Apple's " The Swift Programming Language (Swift 2.2) " with its example code just below it; 这是苹果公司的“ Swift编程语言(Swift 2.2) ”的节选,其示例代码就在其下面;

If the optional value is nil , the conditional is false and the code in braces is skipped. 如果可选值为nil ,则条件为false并且括号中的代码将被跳过。 Otherwise, the optional value is unwrapped and assigned to the constant after let , which makes the unwrapped value available inside the block of code. 否则, 将对可选值进行解包,并在let之后let其分配给常量,这将使解包后的值在代码块内可用。

Here is the sample code for that excerpt; 这是该摘录的示例代码;

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

So for these reasons, I'm thinking that either I'm missing something or that I'm hitting a bug . 因此,由于这些原因,我在想或者我丢失了某些东西,或者正在遇到错误

I've also tried something similar on a Playground, and didn't get a similar error; 我也曾在Playground上尝试过类似的操作,但未收到类似的错误;

在此处输入图片说明

Here is my Swift version; 这是我的Swift版本;

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

If you look at currentTitle , you'll see it is likely inferred to be String?? 如果查看currentTitle ,您可能会发现它很可能是String?? . For example, go to currentTitle in Xcode and hit the esc key to see code completion options, and you'll see what type it thinks it is: 例如,转到Xcode中的currentTitle并按esc键以查看代码完成选项,然后您将看到它认为是什么类型:

在此处输入图片说明

I suspect you have this in a method defining sender as AnyObject , such as: 我怀疑您在将sender定义为AnyObject的方法中有此AnyObject ,例如:

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

But if you explicitly tell it what type sender is, you can avoid this error, namely either: 但是,如果您明确告诉它sender是什么类型,则可以避免此错误,即:

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

Or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM