Created
January 31, 2020 16:15
-
-
Save denisoliveira/f365225397db401ab2d624028cd9cbba to your computer and use it in GitHub Desktop.
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
import Foundation | |
struct AnyKey: CodingKey { | |
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 | |
} | |
} | |
func convertFromDashCase(_ keys: [CodingKey]) -> CodingKey { | |
var key = keys.last?.stringValue ?? "" | |
var parts = key.split(separator: "-").compactMap(String.init) | |
guard parts.count > 1 else { | |
return AnyKey(stringValue: key)! | |
} | |
for (index, part) in parts.enumerated() { | |
if index != 0 { parts[index] = part.capitalized } | |
} | |
key = parts.joined() | |
return AnyKey(stringValue: key)! | |
} | |
let JSON = """ | |
{ | |
"title": "A weekly Swift Blog on Xcode and iOS Development - SwiftLee", | |
"url": "https://www.avanderlee.com", | |
"total-visitors": 378483, | |
"number-of-posts": 47093 | |
} | |
""" | |
let jsonData = JSON.data(using: .utf8)! | |
struct Blog: Decodable { | |
let title: String | |
let url: URL | |
let totalVisitors: Int | |
let numberOfPosts: Int | |
} | |
let decoder = JSONDecoder() | |
decoder.keyDecodingStrategy = .custom(convertFromDashCase(_:)) | |
let blog: Blog = try! decoder.decode(Blog.self, from: jsonData) | |
print(blog.numberOfPosts) // Prints: 47093 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment