6 hours-one coding problem?

Loughy Studios
4 min readAug 5, 2021

As I’ve been told many times, StackOverflow becomes your best friend when you’ve become stuck with a coding issue. Since I am not quite at the level of creating my own apps or working for a company just yet, I have been on the Hacking with Swift forums to look for the issues I’d been having with my day 34 challenge. It wasn’t as straight forward as I’d hoped…

Photo by Mitchell Hollander on Unsplash

We had just gone over animations in the 100 days of SwiftUI challenge and I landed up on day 34 which is part 3 of the animations section. This meant it was the last day of animations and therefore challenge day. We are told to go back to one of our previous apps where we made a guess the flag game -fairly simple and nothing too spectacular in the design field either. The first of the 3 challenges is to have the correct flag button spin around when you click it. This sounds simple enough right? It is. Apart from that we didn’t make individual buttons for our app. We learned about the ForEach loop and we made use of it to create our different flag buttons. This, is why it was not quite the easy challenge.

When it comes to these challenges where I stumble in to an issue, it’s mostly sitting back, reading code and thinking. Not much actually goes on.

Finally after scouring the forums for the help I was seeking, I found the single line of code that got my animation to work on the correct flag button. It was a ternary operator, which apparently isn’t used all too often because it makes your code harder to read? I didn't find this the case as I understand it. Sort of. I get it in that it makes my button spin. However with that, even when I click the wrong button, the correct button always spins. Good and bad because if I had done this on purpose it would be to indicate which flag was actually correct to help the user learn. In my case, it did this all by itself as it was not intended to happen. Yay.

I didn't notice this issue at first and jumped straight into the second challenge which was to make the other two buttons fade to 25% opacity. This also took some thinking and had me thinking of a method that would select the incorrect answers (buttons) and then I could make them disappear. This wasn’t what I did because I got inpatient and went to the forums to get a clue on how I should be tackling this challenge. That wasn’t so successful since I managed to find the single line of code to do this which just so happened to be another ternary operator. The issue with this, which is good because it would have been too easy to just steal some code from someone else, is that the opacity does not reset in the new round. Therefore the new rounds’ incorrect buttons are already at 25% opacity. Kinda lame right. Now it’s my mission to fix that misbehaviour.

I am going to include all the code below. It will get updated as I continue to fix this issues… or make them worse. It would be extremely helpful if any reader has some insight into what I am doing wrong, maybe a tip to send me off in the right direction.

import SwiftUIstruct FlagImage: View {var image: Stringvar body: some View {Image(image).renderingMode(.original).clipShape(Capsule()).overlay(Capsule().stroke(Color.black, lineWidth: 1)).shadow(color: .black, radius: 2)}}struct ContentView: View {@State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled()@State private var correctAnswer = Int.random(in: 0...2)@State private var showingScore = false@State private var scoreTitle = ""@State private var score = 0@State private var animationAmount = 0.0@State private var animationState = falsevar body: some View {ZStack {RadialGradient(gradient: Gradient(colors: [Color.blue, Color.pink]), center: .bottomTrailing, startRadius: 7, endRadius: /*@START_MENU_TOKEN@*/500/*@END_MENU_TOKEN@*/).edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)VStack(spacing: 30) {VStack {Text("Tap the flag of").foregroundColor(.white).padding()Text(countries[correctAnswer]).foregroundColor(.white).font(.largeTitle).fontWeight(.black)}ForEach(0..<3) { number inButton(action: {// Flag tappedif number == self.correctAnswer {}withAnimation() {self.flagTapped(number)self.animationAmount += 360}}){let flagFileName = self.countries[number]FlagImage(image: flagFileName)}.rotation3DEffect(.degrees(shouldRotate(number) ? animationAmount : 0.0),axis: (x: 0.0, y: 1.0, z: 0.0) ).opacity(number != self.correctAnswer && self.animationState ? 0.25 : 1)// Ternary Operators}Spacer().padding(10)//These are the flag buttonsText("Your Score is: \(score)").foregroundColor(.white).fontWeight(.black)}}.alert(isPresented: $showingScore) {Alert(title: Text(scoreTitle), message:Text("Your score is \(score)"), dismissButton: .default(Text("Continue"))  {self.askQuestion()print("Alert scoring worked")})}}func flagTapped(_ number: Int) {if number == correctAnswer {scoreTitle = "Correct"self.score += 1animationState = true}else {scoreTitle = "Wrong, the correct answer is \(countries[correctAnswer])"}showingScore = true}func shouldRotate(_ number: Int) -> Bool {var rotate = falseif number == correctAnswer {rotate = true}return rotate}func askQuestion() {countries.shuffle()correctAnswer = Int.random(in: 0...2)}}// end of bodystruct ContentView_Previews: PreviewProvider {static var previews: some View {ContentView()}}

--

--

Loughy Studios

Tech & self-development writer, programmer. Sharing tips, insights on build & learn in public , positive habits & latest tech trends. @loughystudios -> Twitter