Skip to content

Instantly share code, notes, and snippets.

@waliid
Created March 31, 2023 10:41
Show Gist options
  • Select an option

  • Save waliid/0147eb0e230cca991f81962ee5c5676f to your computer and use it in GitHub Desktop.

Select an option

Save waliid/0147eb0e230cca991f81962ee5c5676f to your computer and use it in GitHub Desktop.
Property wrappers for Date
@propertyWrapper
struct DateFormatter: Codable, Equatable {
var dateString: String?
private let format: String?
var wrappedValue: Date? {
guard let date = dateString else { return nil }
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: date)
}
init(_ format: String) {
self.format = format
}
}
@propertyWrapper
struct MultiDateFormatter: Codable, Equatable {
var dateString: String?
private let formats: [String]?
var wrappedValue: Date? {
formats?.compactMap({ format in
guard let date = dateString else { return nil }
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: date)
}).first
}
init(_ formats: [String]) {
self.formats = formats
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment