Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable 'varname' used before being initialized in SwiftUI [duplicate]

Tags:

swift

swiftui

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.

like image 405
Jeff G Avatar asked Aug 31 '25 01:08

Jeff G


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

like image 83
Predrag Samardzic Avatar answered Sep 02 '25 19:09

Predrag Samardzic