0

I am trying to write a swift function that returns a single element array from a randomly-selected element of a String array (allFruits).

Goal:

let allFruits:[String] = ["Apples", "Oranges", "Pears", "Grapes", "Bananas"]

randomFruit = ["Apple"]

My progress:

let allFruits:[String] = ["Apples", "Oranges", "Pears", "Grapes", "Bananas"]

func randomFruit(arraySource:[String]) -> [String]{
    let randomItem = arraySource.randomElement()
    var singleArray:[String] = []
    return singleArray.append(contentsOf: randomItem)
}

I would then call this with randomFruit(arraySource: allFruits) to get ["Pears"]

The above return statement is giving me the error of:

Cannot convert return expression of type '()' to return type '[String]'

How can I return a random 1-element array from allFruits?

1
  • return singleArray.append(contentsOf: randomItem)-> singleArray.append(contentsOf: randomItem); return singleArray Commented Oct 4, 2022 at 21:01

1 Answer 1

1

randomItem in your code is an optional since .randomElement can return nil. This is confusing the .append() call at the end. The following should solve that issue.

func randomFruit(arraySource:[String]) -> [String]{
    if let item = arraySource.randomElement() {
        return [item]
    } else {
        return []
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.