Exploring Runloop in Swift

Managing Events

Steven Curtis
2 min readMay 16, 2024
Photo by Bruno Nascimento on Unsplash

I’ve previously written an article about Runloop in Swift, and to be honest I’ve never been entirely happy with that article. So I want to make things clear and easy to understand.

Difficulty: Beginner | Easy | Normal | Challenging

Terminology:

RunLoop: A loop that your program enters which is responsible for waiting for events (like user input, timers, or system messages) and dispatching them to the appropriate code for handling. It keeps the program running and responsive to user actions.

The workings of a Runloop

We wish to process user actions in a time-sensitive way. Forcing a user to wait for a response from a tap to a button in an iOS app would be very frustrating for the user, and may even contribute to a feeling of using a broken and inadequate application.

So when we get a time-sensitive event (like user input) the runloop (automatically setup on the main thread) dispatches the event to a hander (something like touchesBegan(_:with:).

It’s then true to say that a runloop enters a sleep state to conserve CPU usage, and in returns control to the main run loop to update views and layout.

--

--

No responses yet