Skip to content

Instantly share code, notes, and snippets.

@mortenbekditlevsen
Created February 14, 2022 11:30
Show Gist options
  • Save mortenbekditlevsen/ea56fb0d04d00c91b5cb3a960d5af11f to your computer and use it in GitHub Desktop.
Save mortenbekditlevsen/ea56fb0d04d00c91b5cb3a960d5af11f to your computer and use it in GitHub Desktop.
import Foundation
struct Wrapper: Codable, Hashable, RawRepresentable, ExpressibleByStringLiteral, CodingKeyRepresentable {
typealias StringLiteralType = String
var rawValue: String
init(rawValue: String) {
self.rawValue = rawValue
}
init(stringLiteral value: String) {
self.rawValue = value
}
}
let test: [Wrapper: Int] = [
"a": 1,
"b": 2
]
let encoded = try JSONEncoder().encode(test)
print("Encoded", String(data: encoded, encoding: .utf8)!)
// outputs: Encoded {"b":2,"a":1}
// without `CodingKeyRepresentable` conformance it prints: Encoded ["b",2,"a",1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment