0

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

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.

2
  • can you print first your gameLetters and check is there any nil Commented Dec 7, 2021 at 9:37
  • you can try this to print gameLetters gameLetters.forEach { print($0) } Commented Dec 7, 2021 at 9:40

1 Answer 1

1

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))
}

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

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.