You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Timer未在作用域中找到,Swift定时器代码报错如何修复?

问题修复方案

问题根源

你在startButton方法内定义的timer是局部变量,作用域仅局限于该方法内部,update方法无法访问到这个变量,因此会触发“Timer can not find in scope”错误。

修复步骤

  1. 将timer声明为类的实例属性,扩大其作用域到整个类;
  2. 在startButton方法中直接给这个属性赋值,无需再用var重新声明。

修复后的完整代码

// 把timer声明为类的实例属性
var timer: Timer?

@IBAction func startButton(_ sender: UIButton) {
    // 直接给类属性赋值,不需要var
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}

@objc func update() {
    if counter > 0 {
        print(counter)
        counter -= 1
        progreesBar.progress = 1.0 - Float(counter)/Float(seconds)
    } else {
        // 现在可以正常访问timer属性了
        timer?.invalidate()
        // 可选优化:invalidate后将timer置为nil,避免悬空引用
        timer = nil
    }
}

额外优化建议

使用selector方式的Timer存在潜在循环引用风险(Timer会持有self,self又持有Timer),可以改用闭包形式的Timer规避:

@IBAction func startButton(_ sender: UIButton) {
    timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
        guard let self = self else { return }
        if self.counter > 0 {
            print(self.counter)
            self.counter -= 1
            self.progreesBar.progress = 1.0 - Float(self.counter)/Float(self.seconds)
        } else {
            self.timer?.invalidate()
            self.timer = nil
        }
    }
}

内容的提问来源于stack exchange,提问作者Majed Alrajab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 22:14:57