gpt4 book ai didi

swift - 没有候选人产生预期的结果

转载 作者:搜寻专家 更新时间:2023-11-01 06:40:04 24 4
gpt4 key购买 nike

我看过这个answer ,但由于我是 Swift 的新手,并且正在遵循应该在斯坦福 CS193 类(class)中使用的代码,所以我有点困惑。

这是一个涉及构建计算器的练习。在模型中我有这些功能:

private func evaluate() -> Double? {
let (result, remainder) = evaluate(opStack)
return result
}

func pushOperand(operand: Double) {
opStack.append(Op.Operand(operand))
return evaluate()
}

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

在 Controller 中,我有这些功能:

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

@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
if let result = brain.pushOperand(displayValue) {
displayValue = result
} else {
displayValue = 0
}
}

在模型中显示“返回评估”的函数 pushOperand/performOperation 旁边,我得到“没有候选评估产生预期的上下文结果类型...”,在 Controller 中的函数 operate/Enter 旁边,我在“让结果”行旁边得到“条件类型的初始化程序必须具有可选类型...”。

我如何纠正这些错误以及导致它们的原因(因为代码在给定的演示文稿中有效)?

最佳答案

要纠正您的错误,您必须指定函数的返回值。

这是因为任何函数声明的工作方式都是设置参数(例如,对于 pushOperand,参数是 'operand' 并且它是 Double 类型),然后您还必须指定函数最后输出的内容(例如对于 evaluate() 它返回一个 Double 类型的值?可选 Double)。指定返回类型的方式是在初始化括号(指定参数的位置)之后使用语法“-> YourType”。

现在这很重要,因为当您将变量设置为函数的返回值时,就像您在行中所做的那样:

if let result = brain.performOperation(operation) {
displayValue = result
} else {
displayValue = 0
}

函数 performOperation 不知道它可以返回一个值,因为您没有指定它,因此 result 的值总是像编译器看到的那样是 N/A。

现在 if let 错误是一个不同的错误。因为您没有为函数指定返回值,所以您也没有指定返回值可以为 nil(可选)。如果 let 要求它“让”的变量的值可以是 nil。

要解决此问题,请尝试:

func pushOperand(operand: Double) -> Double? {
opStack.append(Op.Operand(operand))
return evaluate()
}

func performOperation(symbol: String) -> Double? {
if let operation = knownOps[symbol] {
opStack.append(operation)
return evaluate()
} else {
return nil
}
}

关于swift - 没有候选人产生预期的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36696321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com