0

The following code compiles without error:

import SwiftUI

struct Model {
    let foo: String
    // let bar: URL
}

struct ModelView: View {
    @State var model: Model

    init(model: Model) {
        self.model = model // error here when `Model.bar` is uncommented
    }

    var body: some View {
        Text(model.foo)
    }
}

However, uncommenting the bar property in Model leads to an error:

Variable 'self.model' used before being initialized

in ModellView.init().

Why does this happen? Adding other properties to Model does not cause this problem, e.g. changing the type of bar to String, Int, CGFloat, NSLayoutConstraint and many others works. OTOH, Date causes the same error as URL.

(using Swift 5.7 in Xcode 14.1)

Gereon
  • 17,258
  • 4
  • 42
  • 73
  • 2
    See also [this](https://stackoverflow.com/q/71101108/5133585). The feature of initialising `State` without using the `_` prefix seems to be very buggy. Adding a `URL` in `ModelView` also breaks it. – Sweeper Nov 15 '22 at 10:08
  • My guess is that it breaks if there is anything from outside of the `Swift` module. – Sweeper Nov 15 '22 at 10:09
  • It should be `@Binding var model: Model` when you need write access to the state passed in, e.g. `TextField("", text: item.foo)`. But in your case it's simply `let model: Model` because you only need read access `Text(model.foo)`, body will be called when the `let` or `@Binding var` changes. – malhal Nov 15 '22 at 14:17

1 Answers1

1

Since @State is a property wrapper, you should do that:

import SwiftUI

struct Model {
    let foo: String
     let bar: URL
}

struct ModelView: View {
    @State var model: Model

    init(model: Model) {
        _model = State(initialValue: model)
    }

    var body: some View {
        Text(model.foo)
    }
}
Morniak
  • 958
  • 1
  • 12
  • 37