Chapters

Hide chapters

SwiftUI Apprentice

Second Edition · iOS 16 · Swift 5.7 · Xcode 14.2

Section I: Your First App: HIITFit

Section 1: 12 chapters
Show chapters Hide chapters

Section II: Your Second App: Cards

Section 2: 9 chapters
Show chapters Hide chapters

10. Working With Datasets
Written by Caroline Begbie

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Now that you know how to collect and store user history, you’ll want to present the data in a user-friendly format. In this chapter, you’ll learn how to deal with sets of data.

First, you’ll allow the user to modify and delete the history data. You’ll present the data in a list and use SwiftUI’s built-in functionality to modify the data. Then, you’ll find out how easy it is to create attractive Swift Charts from datasets.

➤ Open the starter project for this chapter.

This project is the almost same as the previous chapter’s challenge project with these changes:

  • On first run of the project on Simulator, when there is no history, the app will run HistoryStore.copyHistoryTestData(), in HistoryStoreDevData.swift. This method copies a sample history.plist file containing three years of data to the app’s Documents directory. Shorter preview data is available by initializing HistoryStore with init(preview: true).
  • HistoryView.swift will get more complicated through this chapter, so subviews are now in separate properties:

Initial HistoryView subviews
Initial HistoryView subviews

  • DateExtension.swift and Exercise.swift contain some new supporting code.
  • Assets.xcassets contains some new colors.

➤ In Simulator, choose Device ▸ Erase All Contents and Settings…. Erase all the contents to ensure that you start with no history data.

➤ Build and run the app, and in the console, you’ll see Sample History data copied to Documents directory, followed by your Documents URL. Tap the History button to see the sample data.

Sample data
Sample data

In the console, you’ll see error messages: ForEach<Array, String, Text>: the ID Burpee occurs multiple times within the collection, this will give undefined results!. The error means that you are displaying non-unique data in a ForEach loop, and ForEach requires each item to be uniquely identifiable. As you can see from your list, you’re displaying each exercise name multiple times.

You’ll first deal with the error and, then, spend the rest of the chapter building up views to edit and format the history data.

Accumulating Data

Skills you’ll learn in this section: Sets; badges

Instead of showing all the exercises on each line, you’ll show a list of dates, with the number of times you’ve performed the exercises accumulated within those dates. Each date will be unique, and each accumulated exercise within that date will also be unique. The ForEach loops will then show unique data with no errors.

Swift Dive: Sets

To accumulate the data, you’ll create a Set of exercises for each day. In Chapter 7, “Saving Settings”, you learned how to use Dictionary, which is a collection of objects that you access with keys. A Set is an unordered collection of unique objects. When you add an object to a Set, the Set adds the object only if it is not already present.

Accumulating the Exercises

➤ In the Model group, open HistoryStore.swift and add a new property to ExerciseDay:

Omiwie pugaeb
Isizea xutain

Epecui cemoek
Emutee tubaah

Lists

Skills you’ll learn in this section: Listing data; deleting items from lists; collapsing hierarchical data; the Edit button

Editable Lists

Being able to edit lists of data is a common requirement. In this app, you may want to reset your daily exercise. Or perhaps you performed some extra exercises at the gym and want to add them to the history list.

Zeej titlxi lajo
Laak mectye fabu

Rarjulh pecoc
Hoksitv suvap

Nce mehabi zidhap
Dmo rikuro nemwut

Qeme hujaloax
Jowa wenelauh

Showing Hierarchical Data

A data hierarchy has a parent and children. In your data, the date is the parent, and the exercises are the children. Previously, you showed the hierarchy by using a ForEach loop embedded inside another ForEach loop.

Rofmcefedo ftiukl
Wuklxukave smoacv

Correcting Row Deletion

Something very odd happens when you swipe left on an exercise to delete it. An entire day disappears.

Lawaqcioduxx mibe
Miwugpeodezf bume

The Edit button

In addition to swipe-to-delete, you should implement an Edit button. This will place the whole list in editing mode so you can delete multiple rows. Apple provides a special button which does all the work for you.

Esuf holxuv
Uxam tecroz

Egag poge
Ocey dugu

Adding Data to the List

Skills you’ll learn in this section: Date picker; inverting colors; button feedback

Ekh vazseh
Ahx qivfoy

KimaWijteq
QavoRewmex

IlwOpotjuyoGaot
AhgOxesheroYien

Shivwa dse xaxpc oyk pouw
Pdekdo ctu marzk occ buuw

Extra Styling

Add a little pizzazz to the calendar view to make it stand out. If you add a shadow to AddHistoryView as a modifier, all the subviews will get a shadow, which isn’t the result you want. Instead, you’ll add a background color to the view, and add a shadow to that.

Omfonj u nkahed ti gfa golegwif saij
Omhasn e jroluc lu fxu nuxoztax ciib

Adding the Exercise Buttons

Open AddHistoryView.swift and add a new view to the file:

Yki ibaldoku nohzupz
Cju umoxkeme yibnojr

Feedback When Tapping a Button

➤ Open EmbossedButton.swift and examine EmbossedButtonStyle. A button configuration has a property isPressed, which tells you whether you’re currently tapping the button. You can check this property and style your button accordingly.

Yle hehfen jwikoq ut fim
Bqu mufxex sgidiv ir sag

Incrementing the Exercise Count

When you tap an exercise, the exercise count for that date should increment.

Oh sv, snet'q e wuc ib tishoof!
Uy bp, qreb'p o yeq ed danzueb!

Charts

Skills you’ll learn in this section: Bar charts; organizing data for charts; line charts; stacked charts

Bar Charts

Bar charts present data using rectangles of different heights.

Tadwp xef ffuhz
Vikph sul cjoyd

Qiily vef kwuvt dlaqagn Niyhl ulq Baxv Vurac
Qaumw fuy qhahr wxejuzw Tisqy efk Pejq Melad

Niovr bvoxk
Cuuyc mwehn

Charting a Week’s Data

Next, you’ll create a bar chart that groups all the exercises by day and shows the latest week’s data.

E qaon's wifdn iw etiyjugoy
I toog'z kepbg ot oracqocas

O saojv kfarp
U taabk cxunz

E kicib-min vsujd
A gucix-tuk tkocx

Line Charts

It’s easy to replace this bar chart with a line chart.

I zuqiv digu trurv
A cevih wema ktesy

A habi snent
O muti gsocp

Other Chart Styles

Try replacing LineMark with PointMark, AreaMark and RectangleMark to see the resulting charts. You can even layer marks by placing one mark after another inside Chart { }.

If ogia pyuqt rerf u violj pfayn
Am ipuu fbafc cewn u souvp sjadx

Stacked Bar Chart

➤ Return Chart and its contents to:

I ksujroq laj mjedh
U nxeffev duk ptuzh

Fukhub jijunn
Mofdeg gahowd

Privacy

Skills you’ll learn in this section: User privacy

Challenge

As you can see, it’s easy to design new charts. Your challenge is to incorporate new charts into your app.

Ruan dgaydiqho
Dueg ldajwilki

E vssgax pexim tovep xain
E rkfgil huroy sukox veum

Key Points

  • A Set is a collection of data where each element is unique. Both Set and Array have initializers to create one from the other.
  • Use List for lists of data. Editing lists is built-in.
  • To show groups of data which you can collapse and expand, use a DisclosureGroup.
  • Swift Charts is a framework that displays your data in gorgeous charts with minimal code.
  • As well as bar charts, you can just as easily create line, point and area charts.
  • You can layer charts on top of each other, such as layering points on top of lines.
  • When you have groups of data, you can stack the data in a single bar. Charts will automatically create different colors for the groups.
  • You can customize any chart legends and colors.

Where to Go From Here?

For more practice with Swift Charts, visit Swift Charts Tutorial: Getting Started

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now