Variable 'varname' used before being initialized in SwiftUI

Viewed 4987

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.

1 Answers

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 _ .

Related