Skip to content

Instantly share code, notes, and snippets.

@ole
Created January 1, 2023 15:43
Show Gist options
  • Save ole/9b2acac2225b5218371a06d9d63295cd to your computer and use it in GitHub Desktop.
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).
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