Реализация таймеров в Swift: Timer, DispatchSourceTimer и CADisplayLink

Чтобы найти информацию о таймерах в Swift при переполнении стека, вы можете выполнить следующие действия:

  1. Перейдите на сайт Stack Overflow ( https://stackoverflow.com ).
  2. Введите «таймер в Swift» в строке поиска.
  3. Нажмите Enter или щелкните значок поиска.

Вот несколько возможных способов реализации таймеров в Swift:

  1. Использование таймера:

    var timer: Timer?
    // Start the timer
    timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
    // Perform your desired action here
    }
    // Stop the timer
    timer?.invalidate()
    timer = nil
  2. DispatchSourceTimer:

    import Dispatch
    var timer: DispatchSourceTimer?
    // Start the timer
    timer = DispatchSource.makeTimerSource()
    timer?.schedule(deadline: .now(), repeating: .seconds(1))
    timer?.setEventHandler {
    // Perform your desired action here
    }
    timer?.resume()
    // Stop the timer
    timer?.cancel()
    timer = nil
  3. CADisplayLink:

    import UIKit
    var timer: CADisplayLink?
    // Start the timer
    timer = CADisplayLink(target: self, selector: #selector(updateTimer))
    timer?.add(to: .current, forMode: .default)
    @objc func updateTimer() {
    // Perform your desired action here
    }
    // Stop the timer
    timer?.invalidate()
    timer = nil