Search code examples
iosswiftstaticnsdatensdateformatter

Static computed variable gets instantiated more than once


I have a date formatter I'm trying to create as a singleton within a UITableViewCell subclass so I've created a computed property like this:

private static var dateFormatter: NSDateFormatter {
    print("here here")
    let formatter = NSDateFormatter()
    formatter.dateFormat = "EEEE h a"
    return formatter
}

The problem is that I'm seeing the print statement more than once, which means it's getting created more than once. I've found other ways to do this (like putting in in an external class, or a class method), but I would love to understand what's happening here. Any ideas?


Solution

  • Your snippet is equivalent to a get-only property, basically it's the same as:

    private static var dateFormatter: NSDateFormatter {
        get {
            print("here here")
            let formatter = NSDateFormatter()
            formatter.dateFormat = "EEEE h a"
            return formatter
        }
    }
    

    If you only want it to run once you should define it the same way you would define a lazy property:

    private static var dateFormatter: NSDateFormatter = {
        print("here here")
        let formatter = NSDateFormatter()
        formatter.dateFormat = "EEEE h a"
        return formatter
    }()