【问题标题】:Swift error: Initializer for conditional binding must have Optional type, not '()'Swift 错误:条件绑定的初始化程序必须具有可选类型,而不是“()”
【发布时间】:2015-12-31 00:25:25
【问题描述】:

我正在参加 iTunes 大学的课程,名为“使用 Swift 开发 iOS 8 应用程序”。在第三个视频中,我遇到了一个视频中没有出现的问题,即使是相同的代码,如下:

class ViewController: UIViewController{

…

@IBAction func operate(sender: UIButton) {
        if userIsInTheMiddleOfTypingANumber{
            enter()
        }
        if let operation = sender.currentTitle {
            if let result = brain.performOperation(operation) { > ERROR HERE
                displayValue = result
            } else {
                displayValue = 0
            }
        }
    } 
…
}

在阅读了很多关于这个错误的解释后,我想问题来自这里:

class CalculatorBrain
{

…
func performOperation(symbol: String) {
        if let operation = knownOps[symbol] {            opStack.append(operation)
        }
    }
}

如果你能帮助我,谢谢!

【问题讨论】:

  • brain.performOperation(operation) 是返回任何东西还是一个 void 函数?
  • 错误是什么?你想让这段代码做什么?
  • performOperation 方法需要返回一个可选类型。 Swift 的错误描述真的很糟糕,但是这个描述得很好
  • func performOperation(symbol: String) -> Int?
  • Leo Dabus:它与 func performOperation(symbol: String) -> Double?谢谢你!!

标签: ios swift itunesu


【解决方案1】:

performOperation 不返回任何内容,需要返回一个可选类型,以便它可以在您的 if let 语句中使用(检查它是否确实返回了一个值),这就是它可能抱怨的地方。

试试:

func performOperation(symbol: String) -> Int? {

这意味着它可以返回一个 Int,然后你的 if let 语句应该是快乐的。

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 2017-01-22
    • 2018-03-25
    • 2016-01-08
    • 2017-04-08
    • 2016-09-23
    相关资源
    最近更新 更多