Understanding Task Modifier in Swift for iOS 15

Mohammad Azam
3 min readJun 25, 2021
Photo by Agung Raharja on Unsplash

As a developer who has worked in React, Flutter and SwiftUI, it is always nice to see that how many SwiftUI features are inspired from existing platforms. All three major platforms (React, Flutter and SwiftUI) have adopted a declarative approach for building user interfaces. This means you can easily transfer your knowledge between React, Flutter and SwiftUI.

In iOS 15 a new task modifier has been introduced, which can be used to perform an operation when the view appears and cancelled when the view disappears. In this post, I will talk about the new task modifier and how it can be used to handle dependencies.

The function onAppear still exists and there are currently no plans to depreciate it. You will learn in this post that task modifier serves a different purpose than onAppear.

Implementation

The main purpose of the task modifier is to await for result from an async operation. This is the reason the task closure is marked with an async keyword. Within the task modifiers you can perform a call to an API and populate your view. Here is a small example:

It is not recommended that you call the API from the View. You should use a pattern like MVVM, Redux, MVC to layer your app.

In the task modifier, we are calling the getTodo function. The getTodo function is an async function, which calls the url, gets the data and returns the task title. Finally, the taskTitle property is assigned with the new title and it gets displayed on the screen.

In most cases, you will use the task modifier to perform an initial request and populate your screen. But task modifier can also handle dependencies. In the next section, you will learn how to invoke the task closure, if any of its dependencies change.

Handling Task Modifier Dependencies

The concept of handling dependencies in task modifier is almost identical to useEffect in React. Take a look at React…

Mohammad Azam

Lead instructor at a coding bootcamp. Top iOS mobile instructor on Udemy. Author of multiple books and international speaker. azamsharp.teachable.com