计时器不在Swift 3.0游乐场中运行

使用 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))

除非有工作运行循环接受输入,否则计时器不会执行任何操作.该计划只是结束.

Timer reference

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.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...