GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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      

Hacking with Swift is sponsored by try! Swift Tokyo.

SPONSORED Ready to dive into the world of Swift? try! Swift Tokyo is the premier iOS developer conference will be happened in April 9th-11th, where you can learn from industry experts, connect with fellow developers, and explore the latest in Swift and iOS development. Don’t miss out on this opportunity to level up your skills and be part of the Swift community!

Get your ticket here

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.