Created
January 1, 2023 15:43
-
-
Save ole/9b2acac2225b5218371a06d9d63295cd to your computer and use it in GitHub Desktop.
Illustrating the differences between encoding through a encoding container (recommended) vs. calling encode(to:) directly on the encoder (generally not recommended).
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 | |
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 containerEncoded = try encoder.encode([ContainerEncoded()]) | |
let directEncoded = try encoder.encode([DirectEncoded()]) | |
String(decoding: containerEncoded, as: UTF8.self) // ["2021-11-18T10:47:54Z"] | |
String(decoding: directEncoded, as: UTF8.self) // [658925237.50108004] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment