Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put DateFormatter() and xxx.dateFormat = "xxx" in SwiftUI

Where should I put the following code in SwiftUI:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"

If I put it outside struct ... {...} I get "Expressions are not allowed at the top level"

If I put it inside I get var body: some View {...} I get Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type.

like image 675
JakobGlieder Avatar asked Dec 06 '25 14:12

JakobGlieder


1 Answers

There are several ways of doing it.

You can create a static property in the view - then you'll always use the same formatter:

struct ContentView: View {
    static let dateFormatter: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd.MM.yyyy"
        return dateFormatter
    }()
    
    ...
}

You can also create a formatter directly in the body and then return some View:

struct ContentView: View {
    var body: some View {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd.MM.yyyy"
        return VStack {
            ... // use the `dateFormatter` as you wish
        }
    }
}
like image 189
pawello2222 Avatar answered Dec 11 '25 15:12

pawello2222



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!