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?
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.
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.
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.
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
}()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With