I am new to swift and am very unfamiliar with Objective-C. Could someone help me convert this to Swift? I got this code from Ray Wenderlich's best iOS practices - http://www.raywenderlich.com/31166/25-ios-app-performance-tips-tricks
Where would you put this code? Would it go in a class file full of global variables?
- (NSDateFormatter *)formatter {
static NSDateFormatter *formatter;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_formatter = [[NSDateFormatter alloc] init];
_formatter.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy"; // twitter date format
});
return formatter;
}
As Rob said, you must be careful with performance creating DateFormatters, use the tips from that WWDC session.
I am doing this as extensions of NSDate and NSDateFormatter (code tested in Swift 2, 3 and 4):
extension NSDate {
func PR2DateFormatterUTC() -> String {
return NSDateFormatter.PR2DateFormatterUTC.stringFromDate(self)
}
//... more formats
}
extension NSDateFormatter {
fileprivate static let PR2DateFormatterUTC: NSDateFormatter = {
let formatter = NSDateFormatter()
let timeZone = NSTimeZone(name:"UTC")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = timeZone
return formatter
}()
//... more formats
}
Usage:
let dateStringUTC = NSDate().PR2DateFormatterUTC()
I've tried to apply the Singleton approach found here. This creates a singleton that could be loaded up with different the different formats you use within your application. For example, you could access it anywhere in your application with formatter.fromDateTime(myString)
let formatter = FormatterFormats()
class FormatterFormats {
var dateTime: NSDateFormatter = NSDateFormatter()
class var sharedInstance:FormatterFormats {
return formatter
}
func fromDateTime(dateString: String) -> NSDate {
return dateTime.dateFromString(dateString)!
}
init() {
dateTime.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
}
}
You could do it like that and move the NSDateFormatter
and the onceToken
outside your function. Then you can do it like in your example:
var theFormatter:NSDateFormatter!
var token: dispatch_once_t = 0
func formatter() ->NSDateFormatter {
dispatch_once(&token) {
theFormatter = NSDateFormatter()
theFormatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
}
return theFormatter
}
But as David suggested, you should take a look at the dispatch_once singleton question.