Created
December 16, 2021 19:46
-
-
Save scottymac/1ab0b52916c7cf9dd9a4ce9062f86ca6 to your computer and use it in GitHub Desktop.
Decodable Property Wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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