Why does the following code get an error with a Date but not a String

Viewed 46

The following code gets a compiler error "Variable 'self.d' used before being initialized"

it's easy to fix, by initializing the @State variable like you're supposed to, e.g.

_d = State(initialValue: test)

but I'm trying to understand the language better, and SwiftUI better, and don't see why it fails, but if I replace Date with String, it compiles just fine.

My best guess is that maybe the compiler is doing some optimization that is reforming the normally invalid syntax into something that works, and it can't do this in some cases.

I'm hoping someone else can give me a better idea about exactly what's going on. Thanks much for your attention :)

import SwiftUI

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

Edit: This works not just with primitive types, but a class that I define myself will work also, if it doesn't contain a Date.

0 Answers
Related