2

Hi i need help with making lazy property.

I have this code:

lazy var dateFormat: DateFormatter =
{
    let formatter = DateFormatter()
    formatter.locale = NSLocale.current
    formatter.dateFormat = "dd/MM/YYYY hh:mm"
    return formatter
}()

And when using it in Text(date, formatter: self.dateFormat)

I am getting this error Cannot use mutating getter on immutable value: 'self' is immutable

2
  • You're declaring it as let, use var. Commented Apr 28, 2020 at 8:51
  • Can do @State lazy var dateFormat ..... ? Commented Apr 28, 2020 at 8:51

3 Answers 3

1

You can use static instead of lazy.

struct Formatter: View {

    var date = Date()

    private static var dateFormat: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = NSLocale.current
        formatter.dateFormat = "dd/MM/YYYY hh:mm"
        return formatter
    }()

    var body: some View {
        Text("\(date, formatter: Self.dateFormat)")
    }
}

Sign up to request clarification or add additional context in comments.

2 Comments

For all who reading this. Please use formatter like this: formatter.setLocalizedDateFormatFromTemplate("dd/MM/YYYY hh:mm") You will get also the correct orientation of the date components for free.
@Tobias template is not a date format. The order of the components doesn't matter as well as the separators. They will be ignored.
1

The answers about using a date formatter in SwiftUI aren't wrong, but none of them correctly handle the localised date format. If you aren't going to use any of the predefined date formats you should use the DateFormatter instance function setLocalizedDateFormatFromTemplate(_ dateFormatTemplate: String).

This lets you pass in the format you want - and cleverly applies the correct localised versions of that format: You can try it out in a Swift Playground:

enter image description here

You can see that the correct locale is used to render the date string.

1 Comment

stackoverflow.com/questions/61476199/… the comment above applies here as well. Adding them to the initial string is pointless
0

You cannot use lazy within SwiftUI view, if you want in this specific case can be used static, as in below example

struct TestView: View {
    static var dateFormat: DateFormatter =
    {
        let formatter = DateFormatter()
        formatter.locale = NSLocale.current
        formatter.dateFormat = "dd/MM/YYYY hh:mm"
        return formatter
    }()

    // ... other code

    // use as TestView.dateFormat

as alternate you can move lazy var dateFormat into related view model class and use it from corresponding instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.