3

I'm back with another question. I was following this guide: https://medium.com/@fs.dolphin/passing-data-between-views-in-swiftui-793817bba7b1

Everything worked from it, but the SecondView_Previews is throwing an error Missing argument for parameter 'message' in call. Here is my ContentView and SecondView

// ContentView
import SwiftUI

struct ContentView: View {
    @State private var showSecondView = false
    @State var message = "Hello from ContentView"
    
    var body: some View {
        VStack {
            Button(action: {
                self.showSecondView.toggle()
            }){
               Text("Go to Second View")
            }.sheet(isPresented: $showSecondView){
                SecondView(message: self.message)
        }
            Button(action: {
                self.message = "hi"
            }) {
                Text("click me")
            }
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
import SwiftUI

struct SecondView: View {
    @State var message: String
    
    var body: some View {
        Text("\(message)")
    }
}
 struct SecondView_Previews: PreviewProvider {
    static var previews: some View {
        SecondView() // Error here: Missing argument for parameter 'message' in call.
    }
 }

It tried changing it to SecondView(message: String) and the error changes to "Cannot convert value of type 'String.Type' to expected argument type 'String'"

Can someone please explain what I'm doing wrong, or how to correctly set up the preview. It all works fine when there's no preview. Thanks in advance!

Harshil Patel
  • 1,318
  • 1
  • 7
  • 26
  • 3
    You must instantiate it with a concrete message string for the preview, e.g. `SecondView(message: "Hello World")` – Martin R Dec 07 '20 at 20:22
  • Inside `SecondView`, for `@State var message: String`, you only define the type and don't supply it with a value yet. That means you'll need to provide that when you initialize `SecondView` as in Martin R's comment above. – aheze Dec 07 '20 at 20:27
  • Alright, thanks I didn't know that. – programmingsushi Dec 07 '20 at 21:04

1 Answers1

3
struct ContentView: View {
    @State var message: String //Define type here 
        var body: some View {
            Text("\(message)")
        }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(message: "Some text") //Passing value here 
    }
}
Harshil Patel
  • 1,318
  • 1
  • 7
  • 26