Make App Pie

Training for Developers and Artists

Checklists in Swift UI

In our last tip, I made a single checkbox in SwiftUI. Let’s learn more about collections in SwiftUI and build a checklist. 

If you download the exercise file, you’ll find an expanded version of last week’s project. Under the model folder, I added some data for our list of pizzas to try.

let checkListData = [
     CheckListItem(title: "Neopolitan"),
     CheckListItem(title: "New York"),
     CheckListItem(title:"Chicago Deep Dish"),

You’ll see that has a struct backing it that stores the title and  an default value of false for each item. 

struct CheckListItem{
     var isChecked: Bool = false
     var title: String

Suppose I wanted to make a list of all my items. Head to CheckListView.  I’d use a list like this: 

List(checkListData){ item in
     CheckView(isChecked: item.isChecked, title: item.title)

However we get a message that CheckListItem does not conform to the Identifiable protocol.  Any object you iterate in Swift UI must have essentially a primary key, a unique identifier. I have two options here: The first is to use existing data, such as the title as my key. I can specify that by adding a parameter of id, set to my title.

 List(checkListData, id:\.title){ item in

The error disappears. However, that means I cannot have two titles the same. If you have unique data this works fine. You have to specify the id in this case, so this makes the checklist less adaptable. 

Our second and better possibility is to adopt the protocol Identifiable.  Head over to the ChecklistItem.  Add the Identifiable protocol to the struct. 

struct CheckListItem:Identifiable{ 

This protocol has one required property named id, which contains a unique identifier. While id can be any hashable type, I’ll make id an integer. 

var id: Int

I’ll change my data to include the id. I’ll add it to the first item. Then cut and paste into the rest. 

let checkListData = [
     CheckListItem(id:0,title: "Neopolitan"),
     CheckListItem(id:1,title: "New York"),
     CheckListItem(id:3,title:"Chicago Deep Dish"),

Our errors have disappeared. 

Change your content view to use the CheckList view. 

Again, I’ll Run on a device instead of the canvas.  You get a nice looking checklist that you can check. This is not yet storing the checkmarks. We’ll look into that in another tip. You’ll find it is best to adopt the Identifiable protocol for iterating in lists. 

The Whole Code

The code for this project is downloadable on GitHub at There’s an accompanying video you can find at LinkedIn Learning.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: