Created
November 18, 2021 10:55
-
-
Save ole/0327f00cda66aa05602f0225708a813f to your computer and use it in GitHub Desktop.
Codable: Encoding through a single-value container vs. calling `encode(to: encoder)` directly
This file contains hidden or 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 | |
struct ContainerEncoded: Encodable { | |
var date: Date = .now | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.singleValueContainer() | |
try container.encode(date) | |
} | |
} | |
struct DirectEncoded: Encodable { | |
var date: Date = .now | |
func encode(to encoder: Encoder) throws { | |
try date.encode(to: encoder) | |
} | |
} | |
let encoder = JSONEncoder() | |
encoder.dateEncodingStrategy = .iso8601 | |
let container = try encoder.encode([ContainerEncoded()]) | |
let direct = try encoder.encode([DirectEncoded()]) | |
String(decoding: container, as: UTF8.self) // ["2021-11-18T10:47:54Z"] | |
String(decoding: direct, as: UTF8.self) // [658925237.50108004] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment