Search code examples
swiftnstimerarc4random

Swift 2.0 Timer for a random number


I need a timer that starts when the the app is started. the timer is for a arc4random that gives me a random number from 1 to 10 and based on that number chooses one of multiple if statements. I also need the timer to reset when the random number is given so that a new random number can be given by the arc4random. I have not yet figured out how to implement the timer and arc4random, but i give an example of the if statements below.

Example:

if timer <= 9  {

print(A)

}

if timer <= 5 {

print(B)
}

if timer >= 4 {

print(C)
}

Solution

  • I am not sure if this is what you are looking for but it sounds like it...

    var timer = NSTimer()
    
    func viewDidLoad() {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "getRandomNumber", userInfo: nil, repeats: true)
    }
    
    func getrandomNumber(){
        let randomNumber = Int(arc4random_uniform(10) + 1)
    
        if randomNumber >= 9 {
            print("...")
        } else if randomNumber < 9 {
            print("...")
        }
        timer.invalidate()
        resetTimer()
    }
    
    func resetTimer() {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "getRandomNumber", userInfo: nil, repeats: true)
    }
    

    when the view loads, the timer begins, where it will call the function getRandomNumber() every 1.0 seconds. getRandomNumber() generates a randomNumber and then depending on what the number is you print or do whatever you want accordingly and then after the if-else statements you invalidate the timer, then call a function called resetTimer, which will start it all over again.

    the random number is generated by Int(arc4random_uniform(10) + 1) where 10 is the upper limit and +1 refers to the starting index. So that will generate numbers between 10 and 1. If you did, for example: Int9arc4random_uniform(20) + 2), it would generate numbers between 20 and 2.