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.
CodePudding user response:
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))
}