Skip to content

Instantly share code, notes, and snippets.

@anelad
Forked from inamiy/struct-CodingKeys
Created July 21, 2018 15:20
Show Gist options
  • Save anelad/2be01cb79e39d441fc853c18ef46b3af to your computer and use it in GitHub Desktop.
Save anelad/2be01cb79e39d441fc853c18ef46b3af to your computer and use it in GitHub Desktop.
Swift 4 Decodable + `struct CodingKeys`
import Foundation
struct User: Decodable {
let name: String
let age: Int?
// private enum CodingKeys: String, CodingKey {
// case name
// case NAME
// }
struct CodingKeys: CodingKey {
let name: String
var stringValue: String {
return self.name
}
init(stringValue: String) {
self.name = stringValue
}
var intValue: Int? {
return nil
}
init?(intValue: Int) {
return nil
}
static let name = CodingKeys(stringValue: "name")
static let NAME = CodingKeys(stringValue: "NAME")
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let n1 = try container.decode(String.self, forKey: .name)
let n2 = try container.decode(String.self, forKey: .NAME)
name = n1 + " " + n2
age = 1
}
// public func encode(to encoder: Encoder) throws {
// throw NSError()
//// var container = encoder.container(keyedBy: CodingKeys.self)
////
//// let splitted = name.split(separator: " ")
//// let first = splitted.first.map(String.init)
//// let second = splitted.last.map(String.init)
//// try container.encode(first, forKey: .name)
//// try container.encode(second, forKey: .NAME)
// }
}
let data = """
{
"name": "hey",
"NAME": "HEY",
}
""".data(using: .utf8)!
let decoder: JSONDecoder = JSONDecoder()
do {
let user: User = try decoder.decode(User.self, from: data)
print(user)
// let encoder = JSONEncoder()
// let encoded = try encoder.encode(user)
// let encodedString = String(data: encoded, encoding: .utf8)!
// print(encodedString)
} catch {
print(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment