Skip to content

Instantly share code, notes, and snippets.

@scottymac
Created December 16, 2021 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottymac/1ab0b52916c7cf9dd9a4ce9062f86ca6 to your computer and use it in GitHub Desktop.
Save scottymac/1ab0b52916c7cf9dd9a4ce9062f86ca6 to your computer and use it in GitHub Desktop.
Decodable Property Wrapper
import Foundation
@propertyWrapper
struct UnixTimeCodedDate {
var wrappedValue: Date?
init(wrappedValue: Date?) {
self.wrappedValue = wrappedValue
}
}
extension UnixTimeCodedDate: Decodable {
init(from decoder: Decoder) {
do {
let unixTime = try TimeInterval(from: decoder)
wrappedValue = Date(timeIntervalSince1970: unixTime)
} catch {
wrappedValue = nil
}
}
}
extension KeyedDecodingContainer {
func decode(_ type: UnixTimeCodedDate.Type, forKey key: Key) throws -> UnixTimeCodedDate {
try decodeIfPresent(type, forKey: key) ?? .init(wrappedValue: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment