Swift 快速开关默认值+;故障:预期返回的函数中缺少返回';字符串';

Swift 快速开关默认值+;故障:预期返回的函数中缺少返回';字符串';,swift,compiler-errors,switch-statement,Swift,Compiler Errors,Switch Statement,我有以下代码: func messageForError(error: ApiErrorType)->String{ switch (error){ case .ApiError(let apiMessage): if let newMessage = apiMessage{ return newMessage } case .NoInternetError: return "Não foi p

我有以下代码:

func messageForError(error: ApiErrorType)->String{
    switch (error){
    case .ApiError(let apiMessage):
        if let newMessage = apiMessage{
            return newMessage
        }
    case .NoInternetError:
        return "Não foi possível estabelecer conexão com o servidor. Você está conectado à internet?"

    case .RequestError:
        fallthrough
    default:
        return "Não se preocupe, já demitimos o estágiario. \nDeseja tentar novamente?"
    }
}
但编译器会打印以下错误:

预期返回“String”的函数中缺少返回

开关有一个默认值,所以所有的大小写都被处理了,我遗漏了什么或者Swift编译器没有那么聪明

如果我删除了故障诊断码,编译器编译时不会出现任何错误:

    func messageForError(error: ApiErrorType)->String{
    switch (error){
    case .ApiError(let apiMessage):
        if let newMessage = apiMessage{
            return newMessage
        }
    case .NoInternetError:
        return "Não foi possível estabelecer conexão com o servidor. Você está conectado à internet?"
    default:
        return "Não se preocupe, já demitimos o estágiario. \nDeseja tentar novamente?"
    }
}

不清楚你是否已经弄明白了这一点。问题不在于switch语句中没有涵盖所有的基础。这是因为并非所有代码路径都返回值。在APIRROR情况下,如果测试失败,则不会执行任何返回。如果在测试后设置了<代码>返回<代码>,代码将编译。

。如果Apimess为零,ApiError没有返回值,考虑添加另一个子句吗?我不能重现这些症状(我可以得到很多其他症状,但不是你描述的那些)。请包括
ApiErrorType
的定义,并确保这正是您遇到问题的代码,并且第二个版本确实有效(不应该)。(正如@Fantini所指出的,apiMessage必须是可选的,否则无法编译。)如果apiMessage不是可选的,为什么要使用
,如果let
?他们是正确的。当你没有任何选项可以打开时,你不能使用if-let。我在玩这个场景时,你已经弄明白了。但不管怎样,这就是: