Implementing Data Passing Techniques in SwiftUI

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

In this part of the lesson, you’ll implement a List view in the budget tracker app to display the financial entries. You’ll start by passing an array of financial-entry objects to the List. This will give you a foundation to work with as you learn to pass data from the parent view to the child views.

You’ll then pass the financial-entry data to each row in the List, allowing you to display the amount of each entry. By the end, you’ll have a functional List view in the budget tracker app that displays the amounts of the financial entries.

Opening the Starter Project

Before you start, make sure you have the starter Xcode project for this module. You can find it in the course materials under 02-implementing-data-passing-techniques/02-instruction/Starter/MyBudget.xcodeproj. Open the Xcode project and then open BudgetTrackerApp.swift to begin.

Passing Data to a List in SwiftUI

In SwiftUI, a List view is commonly used to display a data collection. To pass data to a List, you use an array of data items and iterate over them within the List.

struct ContentView: View {

  // ...

  var body: some View {
    List(entries) { entry in

    }
  }
}

Passing Data From a List to Child Views

Now that you’ve set up the List, it’s time to pass data from the List to its child views. Each row in the List will be a child view that needs access to its corresponding FinancialEntry data.

List(entries) { entry in
  Text("$\(entry.amount, specifier: "%.2f")")
}

List(entries) { entry in
  Text("$\(entry.amount, specifier: "%.2f")")
    .foregroundColor(entry.isExpense ? .red : .green)
}

Video Demo: Implementing Data Passing in the Budget Tracker App

To solidify your understanding of data passing in SwiftUI, the next section will feature a demo video. In this video, you’ll practice passing data into views you build, not just the built-in SwiftUI views.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo: Implementing Data Passing in the Budget Tracker App