Post

Replies

Boosts

Views

Activity

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.
3
0
2.1k
Oct ’15