Created
August 21, 2020 22:30
-
-
Save rwbutler/6323a90b2a24c9b196e19de15589ef13 to your computer and use it in GitHub Desktop.
json-key-decoding-strategy.swift
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 { | |
static let empty = AnyKey(string: "") | |
var stringValue: String | |
var intValue: Int? | |
init?(stringValue: String) { | |
self.stringValue = stringValue | |
self.intValue = nil | |
} | |
init?(intValue: Int) { | |
self.stringValue = String(intValue) | |
self.intValue = intValue | |
} | |
init(string: String) { | |
self.stringValue = string | |
self.intValue = nil | |
} | |
} | |
public extension JSONDecoder.KeyDecodingStrategy { | |
static let convertFromKebabCase = JSONDecoder.KeyDecodingStrategy.custom({ keys in | |
// Should never receive an empty `keys` array in theory. | |
guard let lastKey = keys.last else { | |
return AnyKey.empty | |
} | |
// Represents an array index. | |
if lastKey.intValue != nil { | |
return lastKey | |
} | |
let components = lastKey.stringValue.split(separator: "-") | |
guard let firstComponent = components.first?.lowercased() else { | |
return lastKey | |
} | |
let trailingComponents = components.dropFirst().map { | |
$0.capitalized | |
} | |
let lowerCamelCaseKey = ([firstComponent] + trailingComponents).joined() | |
return AnyKey(string: lowerCamelCaseKey) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment