Proposal for static variables within functions

I don't know if anyone else has already proposed this, but I would like to have support for static local variables within functions. When I want a static local variable or constant within a function, I currently have to wrap it within a struct as such:

func dumpTime() {
  struct Constants {
       static let formatter : NSDateFormatter = {
            let formatter = NSDateFormatter()
            formatter.dateStyle = .MediumStyle
            formatter.timeStyle = .MediumStyle
            return formatter
       }()
  }
  let dateStamp = Constants.formatter.stringFromDate(NSDate())
  print(dateStamp)
}
dumpTime()


However, it would be nice to have the option to just write something like:

func dumpTime() {
  static let formatter : NSDateFormatter = {
       let formatter = NSDateFormatter()
       formatter.dateStyle = .MediumStyle
       formatter.timeStyle = .MediumStyle
       return formatter
  }()
  let dateStamp = formatter.stringFromDate(NSDate())
  print(dateStamp)
}
dumpTime()


I prefer to define variables with as limited scope as possible, and there are times when static variables and constants are limite to functions. Swift effectively already supports this through nested types withing functions as I demonstrated in the the first code snippet. The second code snippet is just a ltitle less verbose and is preferrable when the nested type is really just needed as a container of static variables as in this case.

  • You can add syntactic sugar by adding a computed var with the same name to working example at the top In this example var formatter : NSDateFormatter { get { Constants.formatter } set { Constants.formatter = newValue } }

Add a Comment

Replies

It's not just about verbosity. There are initialization and destruction timing issues that you're glossing over.


Static variables in methods create a more complicated initialization mechanism. Because that static variable you've declared has to get initialized in an orderly manner exactly once.


For a static property in a nested class, that's already taken care of, because the type declaration and loading mechanisms take care of that. After all, that type you declared nested in the method can be initialized pretty much whenever the runtime feels like doing so, and it just has to ensure that the type's name visibility is properly restricted.


So when were you expecting that formatter variable to be initialized and when were you expecting it to be destroyed?

I expect exactly the same initialization mechanism as for static class/struct variables. They get inititialized the first time they are used. This would be no different than in the case where it was wrapped in a struct or class. If the variable isn't used it won't get initialized.