1

SwiftUI state properties should be declared as private. This is good for encapsulating their values from containing views, but prevents a preview from setting a non-default state using the default initializer. For example, this doesn't compile:

struct TemperatureView: View {
    @State private var isHot = false
    
    var body: some View {
        Text(isHot ? "Hot" : "Cold")
    }
}

struct TemperatureView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            TemperatureView(isHot: true)
            TemperatureView(isHot: false)
        }
    }
}

Replacing private with fileprivate results in the same error. How can I preview private view state?

Edward Brey
  • 40,302
  • 20
  • 199
  • 253
  • The question [SwiftUI - PreviewProvider with private var](https://stackoverflow.com/q/64383191/145173) is similar but involves additional aspects such as Core Data. This question focuses just on previewing view state. – Edward Brey Feb 19 '22 at 18:15
  • 1
    The linked question is an exact duplicate since Core Data isn't relevant to the issue. – Joakim Danielson Feb 19 '22 at 18:20
  • 1
    @JoakimDanielson The crux of what is being asked is indeed the same. Still, I thought asking this question might be the best way [to handle an unnecessarily complex question](https://meta.stackexchange.com/q/376416/167867). But I'm not sure and am looking forward to what guidance the community offers. – Edward Brey Feb 20 '22 at 04:07

1 Answers1

5

as it is @State you might want to do:

init() {}

fileprivate init(isHot: Bool) {
    self._isHot = State(initialValue: isHot)
}
ChrisR
  • 9,523
  • 1
  • 8
  • 26
  • Does `self._isHot = State(initialValue: isHot)` have a different effect than `self.isHot = isHot`? – Edward Brey Feb 19 '22 at 18:56
  • 1
    if you want to initialize a @State var you have to do it like this, otherwise nothing happens. – ChrisR Feb 19 '22 at 20:01
  • Got it. Too bad setting up a preview requires so much verbosity. Hopefully, Apple improves this experience some day. – Edward Brey Feb 20 '22 at 03:47
  • The necessary use of the underscore was not obvious to me, but was clarified here https://stackoverflow.com/a/68213830/41728 – Collin Allen Aug 23 '22 at 22:04