Hello
I want to be able to save Date in @AppStorage, and it works however I was wondering what was the difference between these two extensions, which one is better and why?
extension Date: RawRepresentable {
static var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}()
public var rawValue: String {
Date.dateFormatter.string(from: self)
}
public init?(rawValue: String) {
self = Date.dateFormatter.date(from: rawValue) ?? Date()
}
}
and
extension Date: RawRepresentable {
private static let formatter = ISO8601DateFormatter()
public var rawValue: String {
Date.formatter.string(from: self)
}
public init?(rawValue: String) {
self = Date.formatter.date(from: rawValue) ?? Date()
}
}
Thank You!
Is there a better way to save Date in @AppStorage?
One possible solution:
extension Date: RawRepresentable {
public var rawValue: Double {
self.timeIntervalSinceReferenceDate
}
public init?(rawValue: Double) {
self = Date(timeIntervalSinceReferenceDate: rawValue)
}
}
(UPDATE)
I want to be able to initialize it like this
@AppStorage("date") var date = Date()
Sorry, I was missing that Int
or String
is needed for automatic conversion.
Please try this:
extension Date: RawRepresentable {
public var rawValue: String {
self.timeIntervalSinceReferenceDate.description
}
public init?(rawValue: String) {
self = Date(timeIntervalSinceReferenceDate: Double(rawValue) ?? 0.0)
}
}