Swift 有人能解释一下为什么我在更改一行代码时会收到一条错误消息,说我缺少一个返回
这一行没有给我任何错误:Swift 有人能解释一下为什么我在更改一行代码时会收到一条错误消息,说我缺少一个返回,swift,compiler-errors,Swift,Compiler Errors,这一行没有给我任何错误: if pendingBinaryOperation != nil && accumulator != nil { return (accumulator!.digit, true, pendingBinaryOperation!.description(pendingBinaryOperation!.descriptionOperand, accumulator?.literalDescription ?? " "), accumulator?.
if pendingBinaryOperation != nil && accumulator != nil {
return (accumulator!.digit, true, pendingBinaryOperation!.description(pendingBinaryOperation!.descriptionOperand, accumulator?.literalDescription ?? " "), accumulator?.errorMessage)
} else {
return (accumulator!.digit, false, calculationDescription ?? "", accumulator?.errorMessage)
}
但这一行确实给了我一个错误:
if pendingBinaryOperation != nil && accumulator != nil {
return (accumulator!.digit, true, pendingBinaryOperation!.description(pendingBinaryOperation!.descriptionOperand, accumulator?.literalDescription ?? " "), accumulator?.errorMessage)
} else if accumulator!.digit != nil {
return (accumulator!.digit, false, calculationDescription ?? "", accumulator?.errorMessage)
}
信息是:
预期返回的函数(result:Double?,isPending:Bool,description:String,errorMessage:String?)(aka'(result:Optional,isPending:Bool,description:String,errorMessage:Optional)中缺少返回(result:Double?,isPending:Bool,description:String,errorMessage:Optional)我认为在第二个代码中,您将两个返回都它假设可能存在这样一种情况,即它们都不是真的,因此您根本不会得到任何回报。我想到的唯一可能得到此错误消息的原因是您的程序流 在第一种情况下,它总是基于这个
pendingBinaryOperation!=无和累加器!=无
然而,在第二种情况下,对于这样的程序流,
pendingBinaryOperation!=无和累加器!=nil
是False并且也是累加器!。数字!=nil
为False,您的代码无法命中要返回的内容,因此它会给出这样一条错误消息您在第二段代码中有一些未解决的情况
if pendingBinaryOperation != nil && accumulator != nil {
return (accumulator!.digit, true, pendingBinaryOperation!.description(pendingBinaryOperation!.descriptionOperand, accumulator?.literalDescription ?? " "), accumulator?.errorMessage)
} else if accumulator!.digit != nil {
return (accumulator!.digit, false, calculationDescription ?? "", accumulator?.errorMessage)
}
这是你的密码。让我们先来看看累加器
和pendingBinaryOperation
第二种可能的场景:
,累加器!=无
。执行第一条pendingBinaryOperator!=无
,累加器!=nil
。第二条执行完毕pendingBinaryOperator==nil
,累加器==nil
。没有退货pendingBinaryOperator!=零| | pendingBinaryOperator!==无
这是两种没有返回的情况。发生错误是因为第二个表达式不是详尽的 如果第一个和第二个条件都计算为
false
,则没有返回值。这就是错误消息的状态
您需要一个额外的else
分支
if .... {
return ...
} else if ... {
return ...
} else {
return ...
}
或者在末尾使用return
语句
if .... {
return ...
} else if ... {
return ...
}
return ...
如果在
pendingBinaryOperation
和累加器!时输入if语句,将执行哪个分支!。数字
都是零?