Ray Wenderlich Course Part 4 (up to lesson 35)

As promised I'm finding more time to code today! Not much else to say - let's go!

How to Calculate the Difference

So the challenge here is to see what is the difference is between the slider value and the target. Ray explains that we can't just do sliderValue - targetValue as the sliderValue could be higher.



So one way would be to do an if statement!

E.g.

var difference = 0

if sliderValue > targetValue {

difference = sliderValue - targetValue

} else if targetValue > sliderValue {

difference = targetValue - sliderValue

} else {

difference = 0

}

Another way would be if difference is < 0 to then add that total again twice over...but that sounds more fiddly and less logical to me!



Absolutely NAILED IT! Soooo satisfying! :)



Next difference challenge -



var difference = currentValue - targetValue

 if difference < 0 {
            
        
  difference *= -1
      
            

  }

Very simple! I had to get a bit of an idea from Ray but all good! Even better, there's an even simpler way using the abs (absolute) method...

That's really cool! Good to know!

I've also put difference as a 'let' - a constant, as I won't ever need to change it. 

Variables and Constants


Type Inference

This is pretty obvious now - that Swift knows when a type is an int etc. etc. 

Challenge - showing the score

Yes - I love these!

Easy. 

Challenge - tracking rounds


Should be easy again!

It was!

Adding Polish

Specifically, this is to change the alert message etc. 

let title: String
        
        if difference == 0 {
            
            title = "Perfect!"
        } else if difference < 5 {
            title = "Very close - great try!"
        } else if difference < 10 {
            title = "Close - good try!"
        } else if difference < 20 {
            title = "A little bit off!"
        } else if difference < 50 {
            title = "Eeek...you need to be more accurate!"
        } else {
            title = "Oh dear! You have a lot of work to do!"
        }
        

Challenge - bonus points!

This was pretty easy - putting in bonus 100 points for perfect and 5t0 for the very close. I added these to the if statement already there. Good stuff!

So lots of positives. I was able to figure out every challenge and learned some new things too. Key takeaways:

Using if statements in context - very powerful and useful
Use of the 'abs' method to deal with negative numbers!
How the if statement showed an algorithm
Using multiple labels and tracking them all together in a method







Comments

Popular posts from this blog

*Xcode Project Entry 2* F1 Quiz - part 1

Angela Yu Course Part 10 (up to lesson 112)

Angela Yu Xcode 12 Course - Part 7 (lectures 74 to 79)