BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Day 35: Feeding the Preview Provider

Forums > 100 Days of SwiftUI

I'm going nuts trying to figure out what my ContentView Preview Provider wnats from me. I'm sure it's simple, but... I do hope someone can help?

So in my ContentView I made a state variable called numPressed: Int.

In the Preview Provider, it demands that I feed in a value for numPressed -- except it won't take one. It says: "'ContentView' initializer is inaccessible due to 'private' protection level"

So, what the heck eh? I tried using a $, .constant(3), and similar monkey stuff, but I'm just clueless...

   

Show some code, please. It's very difficult to help when we can't see what you're working with.

   

Hi, Like @roosterboy said without the code it's hard to help but im going to take a shot in the dark and say it's because your declaring your var private, instead of

@State private var numPressed: Int

do

@State var numPressed: Int

If that's not it we need to see the code.

   

You should have a @State private var numPressed = 0 or use a @Binding if you are passing in a proprties that going to change or just a let if not

@Binding var numPressed: Int
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(numPressed: .constant(0))
    }
}

or

let numPressed: Int
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(numPressed: 0)
    }
}

   

Thank you all for the speedy replies! I tried each suggestion in turn.

NigelGee nailed it: I simply needed to set an initial value to my variable, not just its type. So this worked: @State private var numPressed = 0 ...but this didn't: @State private var numPressed: Int

Here is the working code:

struct ContentView: View { @State private var numPressed: Int = 3 <- That's all I needed to add was the = 3 !

var body: some View {
   Text("I got nothin'")
}

}

struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }

   

Hacking with Swift is sponsored by Guardsquare

SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.