0

TL:DR

There seems to be a chicken-and-egg paradox in this View initializer.

The Code

This happens often enough to me that I must be missing something fundamental about @State. Namely the compiler seems to be saying I can't set pickerIndex until pickerIndex has been set, and I can't exit the initializer without setting pickerIndex.

enter image description here

(The LetterSelection variable tracks a letter of the alphabet, but I don't think its details are relevant.)

Andrew Duncan
  • 3,553
  • 4
  • 28
  • 55

1 Answers1

2

Note: it is better to provide code "as code", so it could be easier edited

In the described case it needs to initialize not property value but the state wrapper itself, like

self._pickerIndex = State(initialValue: sel.current.idx)
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thank you Asperi. I agree about code, esp. with SwiftUI where it is easy to cut-and-paste runnable examples. In this case I think seeing the (unhelpful) error messages tells a better story. Now, somewhat off-topic I have an ongoing question about your answer of 2020-03-11. I posted it there; no hurry on that. And I have a strange situation where a `View` seems to be laid out _before_ its initializer runs... I will try to isolate and post a small example. It's another case where `@State` behaves non-intuitively. No end to questions. – Andrew Duncan May 07 '20 at 14:13
  • See https://stackoverflow.com/questions/61661581/swiftui-view-apparently-laid-out-before-init-runs for the above-mentioned "strange situation." Your answer here solves the problem there... but why? – Andrew Duncan May 07 '20 at 15:27