Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting error on ForEach when trying to show array

I have a method that gets a random word from an array and converts it into an array of letters, I’m trying to show each letter using ForEach but I get this error.

Cannot convert value of type ‘[Any]’ to expected argument type ‘Binding<C‎>’

var gameLetters = ContentView.getLetters()

...

ForEach(gameLetters) { letter in   //error here
        Text(letter)
}

This is the method

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

static func getLetters() -> Array<Any> {
    let allWords = WordList.wordList
    let randomWord : String! = allWords.randomElement()
    let letters = Array(randomWord)
    return letters
}

If there is any thing I need to elaborate in please tell me.

>Solution :

Compiler is not happy because Any doesn’t conform to protocols Hashable or Identifiable.

Changing getLetters declaration to

static func getLetters() -> Array<Character> {
    let allWords = WordList.wordList
    let randomWord : String! = allWords.randomElement()
    let letters = Array(randomWord)
    return letters
}

will allow the compiler to understand that the return of getLetters() is an array of Characters (Characters conform to Hashable)

You also need to change the ForEach to

ForEach(gameLetters, id: \.self) { letter in
    Text(String(letter))
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading