Lulu wonders why her procedural code doesn't work in Swift's declarative environment!
func resetGame() {
userScore = 0
for _ in usedWords {
withAnimation {
usedWords.remove(at: 0)
}
}
}
Ok, I admit. I made some assumptions that you have a background in procedural programming languages. It seems this way to me because I interpret your code in this way:
Set the userScore to zero
Then for each word in the array, remove the first word.
When removing the word, apply some animation!
Keep going until all the words are removed.
In SwiftUI's declarative world, you should tell Swift to draw a list
using words in the usedWords
array. But Swift should draw the list of words using animation
whenever the newGame
value changes!
This ensures the view
is redrawn with animation
whenever the newGame
boolean is reset.
// RemoveWordAnimation
// Created by Obelix on 5/3/22.
import SwiftUI
struct ShowWords: View {
@State private var newGame = false // For testing only. Force a newGame
// This array changes, based on your Toggle selection
private var usedWords: [String] {
return newGame ? [String]() : ["Lorem", "ipsum", "dolor", "sit", "amet", "consectetur"]
}
var body: some View {
VStack {
Toggle("New Game", isOn: $newGame).padding(.horizontal)
List {
ForEach(usedWords, id: \.self) { someWord in
Text("\(someWord)")
}
// DECLARE this animation happens whenever the newGame variable changes.
// No need to cycle through all the rows, remove each one, and force animation.
} .animation(.easeOut(duration: 0.75), value: newGame)
}
}
}