全局函数中缺少返回,预期在函数中返回'String'消息



我知道这个错误是一个常见的消息,并且已经成为许多帖子的主题。然而,作为一个几天前才开始的纯粹初学者,我无法真正理解其他帖子上的解决方案,也没有了解Switch的含义。因此,该解决方案不能与我一起使用。以下是我的错误块代码:

func responseTo(question: String) -> String {
let lowercasedQuestion = question.lowercased()
if lowercasedQuestion.hasPrefix("hello") {
if lowercasedQuestion.hasPrefix("Hello") {
return "Why, hello there!"
} else if lowercasedQuestion.hasPrefix("where") {
if lowercasedQuestion.hasPrefix("Where") {
return "To the North"
} else {
return "Where are the cookies?"
}
}
}
}

我试着把最后一个其他放在第一个之外,如果我读到它可以改变输出并删除错误,但它没有改变任何东西。我试图在最后一行输入return nil,但出现了错误。我能做什么?请回答。

responseTo(String) -> String函数必须返回一个String。如果参数(问题(不是以";你好";,该函数没有任何要返回的String。

let result: String = responseTo("asd") // error

正如评论中所说,有几种方法可以解决这个问题。如果函数必须返回一个字符串,那么考虑在末尾返回一个默认值。返回值可以是一个空字符串(但无论您的默认值是什么,请确保正确处理它(。

func responseTo(question: String) -> String {
let lowercasedQuestion = question.lowercased()
if lowercasedQuestion.hasPrefix("hello") {
//
} else {
return "" // this will be the default return value
}
}

func responseTo(question: String) -> String {
let lowercasedQuestion = question.lowercased()
if lowercasedQuestion.hasPrefix("hello") {
//
}
return "" // this will also be the default return value
}

另一种方法是返回一个可选字符串(String?(。return nil不适用于responseTo(String) -> String的原因是它必须返回一个字符串。为了能够返回nil,您必须将函数的声明更改为responseTo(String) -> String?

func responseTo(question: String) -> String? { // the "?" after String notifies the compiler that this function can return a String or a nil
let lowercasedQuestion = question.lowercased()
if lowercasedQuestion.hasPrefix("hello") {
//
}
return nil
}

你可以在这里阅读更多关于功能和可选的

最新更新