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

如何在Timer闭包中更新@Published值且无并发警告?

Swift Concurrency警告:Recorder类计时器闭包捕获self的问题

我有以下代码:

class Recorder: ObservableObject {
    @Published var recordingTimeSeconds: TimeInterval = 0
    private var timer: Timer?
    
    init() {}
    
    func startRecording() {
        timer = Timer(timeInterval: 1, repeats: true, block: { t in  
            self.recordingTimeSeconds = t.timeInterval
        })
        
        RunLoop.main.add(timer!, forMode: .common)
    }
}

我的项目启用了-warn-concurrency编译标记,self.recordingTimeSeconds这一行出现警告:

Capture of 'self' with non-sendable type 'Recorder' in a '@Sendable' closure

原本以为以下方案不会产生警告:
编辑说明: 以下方案实际仍会触发相同警告,撰写问题时XCode未显示该警告

方案一:

Task { @MainActor [timeInterval = t.timeInterval] in
    self.recordingTimeSeconds = timeInterval
}

方案二:

DispatchQueue.main.async { [seconds = t.timeInterval] in
    self.recordingTimeSeconds = seconds
}

但我希望找到替代方案,因为使用DispatchQueue或Task可能在后续引发问题。我的场景中,计时器需要无延迟地更新该值。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 13:09:53