DispatchSource compile error: Cannot assign value of type '()' to type 'DispatchSourceTimer?'

After I installed xcode13 and updated pods of my swiftui project by executing pod update, it occurred an unexpected compile error when I tried to run my project.

Cannot assign value of type '()' to type 'DispatchSourceTimer?'

Is this a new bug? or I did something wrong? See my code below:

//use case for counting down time
self.timer = DispatchSource.dispatchTimer(timeInterval: 1, handler: { dispatchTimer in
      self.time -= 1
      if self.time < 0 {
        dispatchTimer?.cancel()
        self.next()
      }
    }, needRepeat: true)
//DispatchSource extension function
public extension DispatchSource {
  class func dispatchTimer(timeInterval: Double, handler: @escaping (DispatchSourceTimer?) -> Void, needRepeat: Bool) {
     
    let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
    timer.schedule(deadline: .now(), repeating: timeInterval)
    timer.setEventHandler {
      DispatchQueue.main.async {
        if needRepeat {
          handler(timer)
        } else {
          timer.cancel()
          handler(nil)
        }
      }
    }
    timer.resume()
  }
}

Please help!

Answered by robnotyou in 690583022

You are not showing all your code, but it looks like...

  • self.timer is a DispatchSourceTimer
  • dispatchTimer(timeInterval:handler:) has no return type

...so your assignment of dispatchTimer() to self.timer will not compile (you are trying to assign a closure, when a DispatchSourceTimer is expected).

Perhaps you intended?

class func dispatchTimer(timeInterval: Double, handler: @escaping (DispatchSourceTimer?) -> Void, needRepeat: Bool) -> DispatchSourceTimer {

Then dispatchTimer() could return "timer", and the assignment would work.

Accepted Answer

You are not showing all your code, but it looks like...

  • self.timer is a DispatchSourceTimer
  • dispatchTimer(timeInterval:handler:) has no return type

...so your assignment of dispatchTimer() to self.timer will not compile (you are trying to assign a closure, when a DispatchSourceTimer is expected).

Perhaps you intended?

class func dispatchTimer(timeInterval: Double, handler: @escaping (DispatchSourceTimer?) -> Void, needRepeat: Bool) -> DispatchSourceTimer {

Then dispatchTimer() could return "timer", and the assignment would work.

DispatchSource compile error: Cannot assign value of type '()' to type 'DispatchSourceTimer?'
 
 
Q