Home > OS >  Create a 1-element array from a random element in a String array
Create a 1-element array from a random element in a String array

Time:10-05

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?

CodePudding user response:

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 []
    }
}
  • Related