Homework 11: Understanding Dynamic List, ForEach, and Identifiable from Mastering SwiftUI.

We’ve worked with lists in a previous lesson, but this time we’ll go a little more in-depth and figure out multiple ways to create lists and extract data from standard arrays, in addition to arrays that contain objects.

Because we already know how to build lists, we’re going to take a different approach with this chapter and focus on two different techniques that involve two different data structures. Let’s get started.

Set Everything Up

  1. Download StatesAndFlags.zip and take a look inside. You should see lots of images of state flags (50 to be exact) and a file named flags.txt.
  2. Create a new project and drag all of the flag images into assets.xcassets
  3. Open flags.txt and take a look. You should see three arrays: stateNames, stateFlags, and allstates.
  4. Create a new Swift, not SwiftUI, file named storage.swift. Copy everything in flags.txt and paste it just below import Foundation in the new Swift file.
  5. Add the states struct shown below to the Swift file that you just pasted everything else into.
  6. Create two additional SwiftUI files named arrays.swift and collection.swift.
  7. Create links from ContentView.swift to arrays.swift and collection.swift.
struct states: Identifiable {
var id = UUID()
var name: String
var image: String
}

Task 1

Follow the model in your Textbook under the heading Creating a List View with Text and Images (chapter 10), use the stateNames and stateFlags arrays, along with the flag images to create a list in arrays.swift, just like the one they have in the book.

Hint: you will need to use Indices and id: \.self as they show you in one of their graphics, but you already have the one that you copied earlier. You also don’t need to include self before your reference to the arrays since you have them stored in their own file.

Task 2

Follow the model in your Textbook under the heading Working with a Collection of Data. This time, use the allstates array to create a new list in collections.swift.

Hint: you will need to create a struct like the one they show in the book (somewhere between figure 8 and figure 9) that includes a unique identifier and variables for the content of the collections (this is easier than it sounds! :).

Clarification:

In the book, they go through the process of extracting a subview in order to create a list. You can do that part if you want to, but it is not required. Both lists (for Task 1 and Task 2) can look exactly the same.