UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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...

2      

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

2      

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.

2      

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)
    }
}

2      

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() } }

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.