Your Second iOS & SwiftUI App

Nov 4 2021 · Swift 5.5, iOS 15, Xcode 13

Part 1: List View Fundamentals

06. Lists

Episode complete

Play next episode

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 05. Challenge: Book Row Next episode: 07. Navigation
Transcript: 06. Lists

Finally! In this episode, you’ve built up enough of your app for it to make sense to incorporate a List! We’ve talked about doing that enough, already! So, let’s go!

Literally, all you need to do is command-click on the BookRow, and choose Embed in List.

  var body: some View {
    List(/*@START_MENU_TOKEN@*/0 ..< 5/*@END_MENU_TOKEN@*/) { item in
      BookRow(book: .init())

And there’s a handful of book rows! Awesome. Lists work great with a range of numbers like this. You could incorporate them into your rows, if you were so inclined…

      BookRow(book: .init(title: "\(item)"))

But what’s more likely, in your apps, is that you’re going to have an array of some model type.

I’ve supplied a Book array for you, in a Library file, which you can find in the materials for this episode. Just drag it right into your project, and make sure “copy if needed” is checked.

There are just two things in here! At the top, what will become an array of sorted books. Right now, it’s just filled with data from this booksCache property. This is where our starter data is.

You’re welcome to replace these with your own books, if you’d like! These are just the ones I have in my own house.

So let’s try using the sorted books of a Library instance, instead of these numbers.

List(Library().sortedBooks) { item in

And there’s an error.The problem is that the list needs data to identify every row. And it doesn’t know how to get that from a Book yet.

There are multiple ways to deal with that, but one of them is to use the id argument.

List(Library().sortedBooks, id: ) { item in

It takes a key path to something that you could use as a Dictionary key. Like a String. And each Book has two of those right now: a title, and an author. Key path syntax is a backslash, followed by a dot.

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

And that preview looks really weird, because each “item” is no longer a number. It’s a book!

{ book in

Go on and supply that to the BookRow.

BookRow(book: book)

That is a List full of the books currently sitting around at my place. For more consistent looking rows, let’s set the line limit on the VStack to 1.


And, as we’re working on improving appearance, let’s add a little vertical padding to those book rows.

      .padding(.vertical, 8)

Hit the Live Preview button - and it’s scrollable! There’s all my books, some with truncated titles. If we want to see the full titles, we’ll need a more detailed view of the data.