How To Add Data To ContentView On Start

By default, ConventView is the file created by Xcode and it’s first that is executed.

Let’s say you have person property inside ContentView.

struct Person {
let name: String
let age: Int

struct ContentView: View {
let person: Person

var body: some View {
VStack {
Text(“Name: \(
Text(“Age: \(self.person.age))

When you try to run it you get an error because the person isn’t created. To inject it you need to open SceneDelegate.swift and above where ContentView, create a person instance, and put it inside ContentView.

let person = Person(name: “Mike”, age: 33)
let contentView = ContentView(person: person)

You’ll need also to add it to ContentView_Preview to run it inside the preview.

struct ContentView_Previews: PreviewProvider {
 static var previews: some View {
ContentView(person: Person(name: “John”, age: 39))

When you run code on the simulator you’ll get Mike and inside Preview you’ll get John.