Anton Platonov
Anton Platonov

Reputation: 389

Function with a CGFloat as a parameter

I am trying to make this function work with a progress bar:

var progressTimer: Timer?
var time: CGFloat = 0

func setProgress(duration: CGFloat) {
    time += 0.1
    progressFront.progress = time / duration
    if time >= duration {
        progressTimer?.invalidate()
    }
}

func updateProgress() {
    progressTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: (#selector(ViewController.setProgress)), userInfo: nil, repeats: true)
}

func pauseUpdateProgress() {
    progressTimer?.invalidate()
}

Calling the function like this and it just does't work:

setProgress(duration: 20)

While if i hardcode it like follows, it works just fine:

func setProgress() {

            time += 0.1
            progressFront.progress = time / 20

            if time >= 20 {
                progressTimer?.invalidate()
            }
        }

What am I doing wrong?

Upvotes: 1

Views: 262

Answers (2)

Rob
Rob

Reputation: 437882

First, when you have a parameter to the Timer handler, it must be the Timer itself:

func setProgress(_ timer: Timer) {
    ...
}

Second, the #selector should indicate what the parameters are to the method, e.g. #selector(setProgress(_:)).

Upvotes: 1

Sulthan
Sulthan

Reputation: 130122

The selector for a Timer can have one parameter but that parameter must be of type Timer. You just cannot pass duration this way.

However, that's exactly why there is a userInfo parameter and you can pass:

... userInfo: ["duration": 20.0], repeats: true)

Even that probably isn't the best solution for you because after pausing, you will have to pass the duration again.

The simplest solution is to save the duration into a property.

var duration: CGFloat = 0

Upvotes: 0

Related Questions