Last active
September 4, 2020 10:41
-
-
Save atierian/047276034dbafbad10f5316bd43cb549 to your computer and use it in GitHub Desktop.
Custom encoding strategy to swap CodingKeys during encoding
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
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