I have a question about Swift.
I am making a quiz app to learn English words and I want to display the words in the Word class once the player gets right like the picture attached below. However, as you can see, the list has many duplicated values. How can I fix that? Thank you in advance.List View
@Query var playerInfos: [PlayerInfo1]
List {
ForEach(Array(Set(playerInfos)), id: .self) { playerInfo in
ForEach(Array(Set(playerInfo.correctWords)), id: .self) { index in
Text("(displayeWord[index].word)")
.foregroundColor(.black)
}
}
}
-----------------
@Model
class PlayerInfo1 {
var playerScore : Int
var correctWords : [Int] // store the index of the words that the player gets right
init(playerScore: Int, correctWords: [Int]) {
self.playerScore = playerScore
self.correctWords = correctWords
}
}
-----------------
class Word : Identifiable {
}
let displayeWord : [Word] = [
Word(word: "Arvo", meaning1: "午後", meaning2: "午前"),
Word(word: "Bin", meaning1: "ゴミ箱", meaning2: "壺"),
Word(word: "Runners", meaning1: "スニーカー", meaning2: "走る人"),
2
Answers
Try this:
You could try a different approach, using a function (or a computed property if you wish) to
calculate
the set of unique words to display, instead of multiple
ForEach
loops in the body of the view.Example code:
If you prefer using a class for
Word
, use: