Skip to content

Instantly share code, notes, and snippets.

@atierian
Last active September 4, 2020 10:41
Show Gist options
  • Save atierian/047276034dbafbad10f5316bd43cb549 to your computer and use it in GitHub Desktop.
Save atierian/047276034dbafbad10f5316bd43cb549 to your computer and use it in GitHub Desktop.
Custom encoding strategy to swap CodingKeys during encoding
struct AnyKey: CodingKey {
var intValue: Int?
var stringValue: String
init(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
init?(intValue: Int) {
self.stringValue = String(intValue)
self.intValue = intValue
}
}
let myCustomEncoder = JSONEncoder()
myCustomEncoder.keyEncodingStrategy = .custom { keys in
if keys.last!.stringValue == "foo" {
return AnyKey(stringValue: "bar"
} else {
return keys.last!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment