Skip to content

Instantly share code, notes, and snippets.

@akio0911
Last active April 11, 2018 12:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akio0911/1e7168ff9f0a67847be0a7084f2a98cb to your computer and use it in GitHub Desktop.
Save akio0911/1e7168ff9f0a67847be0a7084f2a98cb to your computer and use it in GitHub Desktop.
Dateのextensionに依存性注入してみる
extension Date {
struct Extension {
let date: Date
struct Dependencies {
let calendar: Calendar
let locale: Locale
let timeZone: TimeZone
}
let dateFormatter: DateFormatter
init(date: Date, dependencies: Dependencies? = nil) {
self.date = date
self.dateFormatter = {
let formatter = DateFormatter()
formatter.calendar = dependencies?.calendar ?? Calendar.current
formatter.locale = dependencies?.locale ?? Locale.current
formatter.timeZone = dependencies?.timeZone ?? TimeZone.current
return formatter
}()
}
func string(dateStyle: DateFormatter.Style = .none,
timeStyle: DateFormatter.Style = .none) -> String
{
dateFormatter.dateStyle = dateStyle
dateFormatter.timeStyle = timeStyle
return dateFormatter.string(from: date)
}
}
var ex: Extension {
return Extension(date: self)
}
// 依存性注入
func ex(calendar: Calendar,
locale: Locale,
timeZone: TimeZone) -> Extension
{
let dependencies = Extension.Dependencies(
calendar: calendar, locale: locale, timeZone: timeZone)
return Extension(date: self, dependencies: dependencies)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment