0

I have array with int values:

var array = [1,82,17,29,74,94,76,97,48,78,88,20,31]

And action:

@IBAction func action(_ sender: Any) {
        print("i")
    }

I want to my action to be called for values in array.

For example: first time action calls after 1 seconds, next time after 82 seconds, and next after 17 seconds. And etc...

How to do it?

2 Answers2

1

Use the below code to achieve this.

    var count = 0
    let seconds = array[count] // get initial value
    _ = Timer.scheduledTimer(timeInterval: seconds, target: self, selector: #selector(callMethod), userInfo: nil, repeats: false)

@objc func callMethod() {
    print("CallMethod....")
    count += 1
    if count < array.count {
    let nextTime = array[count] // get next time value
    _ = Timer.scheduledTimer(timeInterval: nextTime, target: self, selector: #selector(callMethod), userInfo: nil, repeats: false)
 }
}
vivekDas
  • 1,248
  • 8
  • 12
  • `Unary operator '++' cannot be applied to an operand of type '@lvalue Int'` in this line` count++` –  Jul 24 '18 at 07:41
1

Its better to use Timer in this case. Here you can find how to use timer in swift Timer Example. In update method of example just reschedule timer with new seconds value.

Muhammad Usman
  • 200
  • 1
  • 14