Timers are a great way to run code on a repeating basis, and iOS has the
Timer class to handle it for you. First, create a property of the type
Timer!. For example:
var gameTimer: Timer!
You can then create that timer and tell it to execute every five seconds, like this:
gameTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true)
runTimedCode selector means that the timer will call a method named
runTimedCode() every five seconds until the timer is terminated, so you'll need to replace that method name with whatever you want to call – and don’t forget to mark it using
Important note: because your object has a property to store the timer, and the timer calls a method on the object, you have a strong reference cycle that means neither object can be freed. To fix this, make sure you invalidate the timer when you're done with it, such as when your view is about to disappear:
Available from iOS 2.0 – see Hacking with Swift tutorial 20
Did this solution work for you? Please pass it on!
Other people are reading…
About the Swift Knowledge Base
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Test your Swift today
Think you know Swift? My book Swift Coding Challenges will put your Swift skills to the test – it's perfect for job interviews and more!