Swift 3.0 游乐场中的计时器不 运行
Timer does not run in Swift 3.0 playground
使用 Swift 3.0 在操场上工作我有这个代码:
struct Test {
func run() {
var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { timer in
print("pop")
}
}
}
let test = Test()
test.run()
但没有任何内容打印到控制台。我读过 How can I use NSTimer in Swift? 并且我在在线答案和教程中看到的大部分计时器用法都涉及选择器,所以我尝试了这个:
class Test {
func run() {
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.peep), userInfo: nil, repeats: false)
}
@objc func peep() {
print("peep")
}
}
let test = Test()
test.run()
似乎仍然没有任何内容打印到控制台。如果我添加 timer.fire()
,那么我会得到控制台打印,但显然这违背了目的。 我需要更改什么才能使计时器达到 运行?
编辑:
所以在我为我的 Test
结构调用 run
方法后添加 CFRunLoopRun()
就成功了。非常感谢那些回答的人,尤其是@AkshayYaduvanshi(他的评论将我指向 CFRunLoopRun()
)和@JoshCaswell(他的回答提出了我的计时器只适用于 运行 循环的事实)。
您需要开始一个 运行 循环。
RunLoop.main.run(until: Date(timeIntervalSinceNow: 3))
计时器不做任何事情,除非有一个正在工作的 运行 循环接受输入。程序简单结束。
Timers work in conjunction with run loops. [...] it fires only when one of the run loop modes to which the timer has been added is running and able to check if the timer’s firing time has passed.
如果您允许 Playground 通过 PlaygroundSupport
无限期 运行:
,您的第一个版本就可以工作
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { timer in
print("Timer Fired at: \(timer.fireDate)")
}
手动添加 运行 循环也可以,有时可能需要,但在您的情况下,这个简单的指令足以使计时器正常工作。
使用 Swift 3.0 在操场上工作我有这个代码:
struct Test {
func run() {
var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { timer in
print("pop")
}
}
}
let test = Test()
test.run()
但没有任何内容打印到控制台。我读过 How can I use NSTimer in Swift? 并且我在在线答案和教程中看到的大部分计时器用法都涉及选择器,所以我尝试了这个:
class Test {
func run() {
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.peep), userInfo: nil, repeats: false)
}
@objc func peep() {
print("peep")
}
}
let test = Test()
test.run()
似乎仍然没有任何内容打印到控制台。如果我添加 timer.fire()
,那么我会得到控制台打印,但显然这违背了目的。 我需要更改什么才能使计时器达到 运行?
编辑:
所以在我为我的 Test
结构调用 run
方法后添加 CFRunLoopRun()
就成功了。非常感谢那些回答的人,尤其是@AkshayYaduvanshi(他的评论将我指向 CFRunLoopRun()
)和@JoshCaswell(他的回答提出了我的计时器只适用于 运行 循环的事实)。
您需要开始一个 运行 循环。
RunLoop.main.run(until: Date(timeIntervalSinceNow: 3))
计时器不做任何事情,除非有一个正在工作的 运行 循环接受输入。程序简单结束。
Timers work in conjunction with run loops. [...] it fires only when one of the run loop modes to which the timer has been added is running and able to check if the timer’s firing time has passed.
如果您允许 Playground 通过 PlaygroundSupport
无限期 运行:
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { timer in
print("Timer Fired at: \(timer.fireDate)")
}
手动添加 运行 循环也可以,有时可能需要,但在您的情况下,这个简单的指令足以使计时器正常工作。