Home > Software engineering >  Missing return in global function expected to return 'String' message in a function
Missing return in global function expected to return 'String' message in a function

Time:07-28

I know this error is a common message and has already been the subject of many posts. However, as a pure beginner who just started days ago, I can't really understand the solution on other posts, and also haven't learned what Switch means. Thefore, that solution can't be used with me. Here's my block code getting the error :

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?"
            }
        }
    }
}

I tried to put the last else outside the first if since I read it could change the output and remove the error, but it didn't change anything. I tried to enter return nil on the last line, but had an error. What can I do? Any answer appreciated.

CodePudding user response:

Your responseTo(String) -> String function must return a String. You must consider this case, if the parameter (question) doesn't start with "hello", the function doesn't have any String to return.

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

As stated in the comments, there are several ways to solve this. If your function must return a string, then consider returning a default value at the end. The return value can be an empty string (but whatever your default value is, make sure to handle it properly).

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

or

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

Another way is to return an Optional String (String?). The reason why return nil doesn't work for responseTo(String) -> String is because it must return a string. To be able to return a nil, you will have to change the declaration of your function to 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
}

you can read more about function here and optional here

  • Related