'Swift Timer inside class not working as expected
I am having difficulty understanding why a Timer works outside of a class but not inside. I assume it has something to do with scope but can not find any resource that has help me understand the problem.
Here is my playground code:
import UIKit
import Dispatch
// Timer inside a class
print ("\nStarting Class based Timer Section\n")
class mytest {
init () {
print ("mytest Classs init()")
}
func starttimer(){
print ("mytest Classs starttimer()")
let timer = DispatchSource.makeTimerSource()
timer.setEventHandler() {
self.doIt()
print ("y")
}
timer.schedule(deadline: .now(), repeating: 1, leeway: .nanoseconds(1))
timer.activate()
}
func doIt() {
let wherefrom = "Inside"
print( "\(wherefrom) of Class")
}
}
var tst = mytest()
tst.starttimer()
// Stand alone timer works outside of a class
print ("\nStarting Stand alone Timer Section\n")
func doIt(){
let wherefrom = "Outside"
print( "\(wherefrom) of Class")
}
let timer = DispatchSource.makeTimerSource()
timer.setEventHandler() {
doIt()
print ("x")
}
timer.schedule(deadline: .now(), repeating: 1, leeway: .nanoseconds(1))
timer.activate()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
