Last active
May 13, 2020 10:21
-
-
Save williamhqs/993fb0d4a74d5ac1fd0de4659fb40524 to your computer and use it in GitHub Desktop.
ProperyWrapper decode
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 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