Is there a good/neat way to organize formatters that are being repeated across different files? I find myself having to implement the same lines of code for different classes. Should I just put the repeated code in a separate file and give it global access? Is it better to create a class/struct to hold these formatters? I may be overthinking this but I would like to learn a good method and stick to it as I work on different projects.
For example, the code being repeated looks like this:
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
return formatter
}()
You can extend Formatter
class and declare your date formatters as static properties. This way you can access the same instance of them anywhere in your code. Note that you should not use a fixed format when displaying the date to the user. You should use date and time style to display it localized based on the user device locale and settings. Btw when using a fixed date format you should set the locale to "en_US_POSIX":
extension Formatter {
static let mmddyyyy: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MM/dd/yyyy"
return formatter
}()
static let shortDate: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
return formatter
}()
static let mediumDate: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
}
Formatter.mmddyyyy.string(from: Date()) // "06/24/2020"
Formatter.shortDate.string(from: Date()) // "6/24/20"
Formatter.mediumDate.string(from: Date()) // "Jun 24, 2020"