Skip to content

Instantly share code, notes, and snippets.

@Sorix
Last active April 20, 2023 10:43
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 Sorix/3e9f3fea37e2f86bc182f7b05714e676 to your computer and use it in GitHub Desktop.
Save Sorix/3e9f3fea37e2f86bc182f7b05714e676 to your computer and use it in GitHub Desktop.
snake_case to camelCase Swift Decodable
import UIKit
enum InteractionCode: String, Decodable {
case PROCEED, abort, tryOtherNetwork, TRY_OTHER_ACCOUNT, RETRY, RELOAD, VERIFY
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let jsonString = try container.decode(String.self)
var camelCasedString = String()
for (index, stringComponent) in jsonString.lowercased().split(separator: "_").enumerated() {
if index == 0 {
camelCasedString += stringComponent
} else {
camelCasedString += stringComponent.capitalized
}
}
if let code = InteractionCode(rawValue: camelCasedString) {
self = code
} else {
let context = DecodingError.Context(codingPath: container.codingPath, debugDescription: "Unable to find enumeration case for " + jsonString)
throw DecodingError.typeMismatch(Self.self, context)
}
}
}
// MARK: - Run
struct TestJson: Decodable {
var code: InteractionCode
}
let json = "{ \"code\": \"TRY_OTHE_NETWORK\" }".data(using: .utf8)!
let decoded = try! JSONDecoder().decode(TestJson.self, from: json)
print(decoded)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment