Skip to content

Instantly share code, notes, and snippets.

@ole
Created November 18, 2021 10:55
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 ole/0327f00cda66aa05602f0225708a813f to your computer and use it in GitHub Desktop.
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
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