How to perform extract subview operation?

Hi everyone,

I want to perform the tutorial from video WWDC19 - 204. Here is an example of building the "Rooms" application. At 11 minutes, the author of the video, Jacob Xiao, shows how he performs the extract subview operation. But when I try to repeat this operation an error occurs - Cannot find 'room' in scope.

My code and code of Jacob Xiao are the same.

import SwiftUI

struct ContentView: View {

    var rooms: [Room] = []    

    var body: some View {

        NavigationView {            

            List(rooms) { room in

                ExtractedView()
            }          

            .navigationBarTitle(Text("Rooms"))
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(rooms: testData)
    }
}
struct ExtractedView: View {
    var body: some View {
        NavigationLink(
            destination: Text(room.name)) { // Cannot find 'room' in scope

            Image(room.thumbnailName)
                .cornerRadius(8)
            VStack(alignment: .leading) {
                Text(room.name)
                Text("\(room.capacity) people")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
            }
        }
    }
}

I think the reason is that SwiftUI on my computer is a newer version, so some of the previous functions may not work.

Could you tell me how to perform this subview extract operation today?

Accepted Answer

This isn’t a new thing in SwiftUI. It’s more to do with Swift and structs.

The error message is saying that it can’t find the variable room inside itself (as a property of the struct). You need to add this property called room to your ExtractedView and pass this in from your ContentView, like this:

struct ExtractedView: View {
  let room: Room // now it knows what 'room' is

  var body: some View { … }
}


In ContentView:

List(rooms) { room in
  ExtractedView(room: room) // give the view the room it needs to show
}

Thank you so much! It works!

P.S. But one question remained with me. Why does Jacob's code work without this?

Below is a screenshot of his code.

How to perform extract subview operation?
 
 
Q