23

The following code in the Xcode playground produces the error in the subject:

import SwiftUI

struct Test2 {
    var i: Int64
    var j: UUID
}

struct Test {
    @State private var t: Test2
    
    init(_ test: Test2) {
        t = test // Variable 'self.t' used before being initialized
    }
}

Obviously, I'm not using t, I'm assigning it a value.

If I remove var j: UUID from the Test2 struct, the error goes away.

In my actual code, the Test struct is a view, but that's not necessary to generate the error.

Jeff G
  • 1,996
  • 1
  • 13
  • 22
  • Where is the Test2 coming from in the initializer? – matt Jul 01 '21 at 21:43
  • @matt From a consumer of the Test struct: `let myTest = Test(Test2(i: 0, j: UUID())` – Jeff G Jul 01 '21 at 21:51
  • But then you need to show that. – matt Jul 01 '21 at 21:55
  • 3
    @matt I don't see its relevance. The caller is immaterial. If you enter the code into a playground, you'll get the error. – Jeff G Jul 01 '21 at 21:57
  • Without a value for the `test:` parameter I would never have expected to compile in the first place. You need at least to show code that stands a _chance_ of compiling. – matt Jul 01 '21 at 22:24
  • 1
    @matt It compiles fine with the accepted answer. No need for the consumer of the `test struct`. – Jeff G Jul 02 '21 at 17:00

1 Answers1

68

This should work:

init(_ test: Test2) {
    _t = State(initialValue: test) // Variable 'self.t' used before being initialized
}

@State is a property wrapper, so you need to assign value to the underlying property, thus _ .

Predrag Samardzic
  • 2,661
  • 15
  • 18