I have the following code:
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)
}
}
I have the -warn-concurrency
compiler flag enabled in my project. The line self.recordingTimeSeconds
gives me the following warning: Capture of 'self' with non-sendable type 'Recorder' in a '@Sendable' closure
One solution that does not give warnings is:
EDIT: The solutions below do give the same warning. XCode just didn't want to show them to me at the time of writing this question
Task { @MainActor [timeInterval = t.timeInterval] in
self.recordingTimeSeconds = timeInterval
}
Alternatively
DispatchQueue.main.async { [seconds = t.timeInterval] in
self.recordingTimeSeconds = seconds
}
But I would like to see an alternative solution since I feel like using a DispatchQueue
or Task
might introduce issues later. The timer in my case needs to update the value without any possible delays.