UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

WithAnimation location in code question

Forums > 100 Days of SwiftUI

Hello,

Working through Project 6 and refactoring the Guess The Flag game I was wondering if someone could explain why one code works and one doesn't. I had to find other peoples solutions on GitHub unfortuntely I couldn't figure this one out on my own. The ternanry operator on the animation blew my mind. I get it now.

This code below works and animates the correct flag. What I found to make it work in my code is that the winAnimation has to be below the function call of flagTapped

ForEach(0..<3) { number in
                        Button{

                            // Flag was tapped
                            flagTapped(number)

                            withAnimation{
                                isRotating += 360
                                scaleAmount = 0.5
                            }

                            gameQuestionCount += 1

                            if gameQuestionCount >= 8 {
                                gameComplete = true
                            }
                        } label: {
                            FlagImage(flagString: countries[number])
                        }
                        // Project 6 challenge for rotating the correct flag
                        .rotation3DEffect(.degrees(number == buttonNumber ? isRotating : 0.0),
                                          axis: (x:0, y: 1, z: 0 ))
                        // Scale incorrect answers to 0.5
                        .scaleEffect(number == correctAnswer ? 1 : scaleAmount, anchor: .center)

If the withAnimation is above the function call the wrong flag will get animated. Usually the animation is off by one. What I mean by that is if the first correct answer is button 0 nothing rotate. The next question if the correct flag is button 1 button 0 rotates and so on.

Can anyone eplain why this is?

Thank you.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.