Passing Data
Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 36 of 50.
A detail screen is usually its own view struct with a property for the data it shows:
struct RecipeDetail: View {
let recipe: Recipe
var body: some View {
Text("Ready in \(recipe.minutes) minutes")
.navigationTitle(recipe.name)
}
}Swift gives the struct an initializer with a parameter for each stored property, so RecipeDetail(recipe: pancakes) creates it. In a list, each link passes its own row's data:
List(recipes) { recipe in
NavigationLink(recipe.name) {
RecipeDetail(recipe: recipe)
}
}Every row gets a link to a detail screen for its recipe. The detail view does not need to know about the list at all.
Challenge
MediumFinish RecipeDetail: it shows Ready in 15 minutes (using the recipe's minutes) in a text with the identifier time, and uses the recipe's name as its title. Then make each list row a NavigationLink titled with the recipe's name that opens RecipeDetail for that recipe.
Try it yourself
import SwiftUI
@main
struct CoddyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction to SwiftUI
Practice on your own: Swift playground