Search code examples
swiftuidateformatter

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.


Solution

  • 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
            }
        }
    }