3

I have a code below, but I am yielding an error that says

missing return in a function expected to return 'String'

func returnMultipleGreetings (name: String...) -> String {
    for names in name {
        return names
    }
}

How do I edit this code to remove the error?

2
  • You have to return in the scope of the function, you make a variable that can hold what you're looping through and then return it. Commented Feb 5, 2016 at 3:34
  • You have to have a String returned for all exit paths. So you need a return after your loop in case some logic in the loop hits the return. In your example you would always return the first value. Your question is also confusing because you have switched the plurality of "names" and "name". Commented Mar 15, 2018 at 18:53

2 Answers 2

5

Try source code:

func returnMultipleGreetings (name: String...) -> String {
    var result = ""
    for names in name {
        result = names
    }
    return result 
}

Hope it's OK.

Sign up to request clarification or add additional context in comments.

Comments

4

You must return within the scope of the function. NOT within the scope of the for-loop, which is where you currently have it. If you are not familiar with "scope" then do some reading as it is an important topic to understand. As of right now, returnMultipleGreetings cannot "see" return names. The following should fix your error...

func returnMultipleGreetings (name: String...) -> String {
     for names in name {
   //iterate thru array within loop
     }
  //return AFTER loop finishes
 return names
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.