1

I have a game that is based on attempts rather than score. And I wish to display a pop up every 10 attempts. What is the best way, using Swift, to calculate every 10 intervals of something?

Currently I call a function to increment the attempts value which includes: gamesPlayedSaved += 1. The closest question I found on here uses timers, which wouldn't work in my case.

So far, I have this (WHICH IS EXTREMELY UGLY):

if(gamesPlayedSaved == 10 ||
                    gamesPlayedSaved == 20 ||
                    gamesPlayedSaved == 30 ||
                    gamesPlayedSaved == 40 ||
                    gamesPlayedSaved == 50 ||
                    gamesPlayedSaved == 60 ||
                    gamesPlayedSaved == 70 ||
                    gamesPlayedSaved == 80 ||
                    gamesPlayedSaved == 90 ||
                    gamesPlayedSaved == 100){
    // call pop up
}

And it also doesn't account for any intervals over 100.

zoul
  • 102,279
  • 44
  • 260
  • 354
Reanimation
  • 3,151
  • 10
  • 50
  • 88

3 Answers3

2

This can be solved using maths. You just need to decide whether gamesPlayedSaved is a multiple of 10. To do this, find the remainder of gamesPlayedSaved / 10 using the modulo operator % and check if it is 0:

if gamesPlayedSaved % 10 == 0 && gamesPlayedSaved > 0 {
    // show pop up
}

Alternatively, reset the counter every time it reaches 10:

if gamesPlayedSaved == 10 {
    // show pop up
    gamesPlayedSaved = 0
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

use modulus %. if (gamesPlayedSaved % 10 == 0)

It will finds the remainder after division of 10

xmhafiz
  • 3,482
  • 1
  • 18
  • 26
1

Take a look at this:

for i in 1...100 {
    if i % 10 == 0 {
        print("Yep: \(i)")
    }
}

Which outputs:

Yep: 10
Yep: 20
Yep: 30
Yep: 40
Yep: 50
Yep: 60
Yep: 70
Yep: 80
Yep: 90
Yep: 100

The % operator is called modulo, it returns the remainder when dividing a number A with number B. In your case you are interested in the cases when the number of games played is divisible by 10, ie. numberOfGamesPlayed % 10 == 0.

zoul
  • 102,279
  • 44
  • 260
  • 354