Skip to content

Instantly share code, notes, and snippets.

@williamhqs
Last active May 13, 2020 10:21
Show Gist options
  • Save williamhqs/993fb0d4a74d5ac1fd0de4659fb40524 to your computer and use it in GitHub Desktop.
Save williamhqs/993fb0d4a74d5ac1fd0de4659fb40524 to your computer and use it in GitHub Desktop.
ProperyWrapper decode
import UIKit
let jsonString =
"""
{
"name": "Tim",
"age": "28"
}
"""
@propertyWrapper
struct Age: Codable {
var age: Int = 0
var wrappedValue: Int {
get {
return age
}
set {
age = newValue * 10
}
}
}
struct People: Codable {
var name: String
@Age var age: Int
}
extension People {
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
name = try values.decode(String.self, forKey: .name)
age = Int(try values.decode(String.self, forKey: .age)) ?? 0
}
}
let jsonData = jsonString.data(using: .utf8)!
let user = try! JSONDecoder().decode(People.self, from: jsonData)
print(user.name)
print(user.age)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment