Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 506
Julian B. Avatar asked May 18 '16 22:05

Julian B.


People also ask

Can value of static variable be changed?

Output will be 12 Yes, values of the static variables can be changed. It is said static because only 1 copy or the original copy of a static variable is shared by all objects using it, whereas for non-static variables each object have its own copy of that variable.

What is a computed or calculated property in a class in Swift?

Computed properties are part of a family of property types in Swift. Stored properties are the most common which save and return a stored value whereas computed ones are a bit different. A computed property, it's all in the name, computes its property upon request.

What is instance property in Swift?

In Swift, properties are associated values that are stored in a class instance. OR we can say properties are the associate values with structure, class, or enumeration. There are two kinds of properties: stored properties and computed properties. Stored properties are properties that are stored in the class's instance.


1 Answers

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
}()
like image 51
dan Avatar answered Nov 24 '22 02:11

dan