J. Doe J. Doe -4 years ago 90
Swift Question

Timer is giving me random numbers in return

func executeSpawningStar(startPosition: CGPoint) {
print(startPosition)
}


This function gets executed by this lines:

gameTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(executeSpawningStar), userInfo: (startPosition: 0, 0), repeats: true)


This is the print:

(1421871380267.49, 9.22337203685478e+18)
(1421902263851.49, 9.22337203685478e+18)
(1421902263851.49, 9.22337203685478e+18)


How is this even possible when I specific say any random number? I see any number inserted returns this very random numbers. How come?

Answer Source

You are doing this all wrong. The parameter to the executeSpawningStart function must be the timer. It can't be anything else. You then get the start position from the timer's userInfo property.

So you need:

func executeSpawningStar(_ timer: Timer) {
    if let startPosition = timer.userInfo as? CGPoint {
        print(startPosition)
    }
}

This assumes that the userInfo you setup when creating the timer is actually a CGPoint (which I based on your original executeSpawningStar method.

But in your call to scheduledTimer... you are not actually passing a CGPoint to the userInfo parameter. It appears to be some sort of tuple. You probably want to pass CGPoint(x: 0, y: 0) instead of (startPosition: 0, 0).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download