I want to decode the JSON string into People
as below. The age
is number(Int
) type, and the below code get error:
"Expected to decode Dictionary<String, Any> but found a number instead."
I think it means the @Age
was treated as Dictionary<String, Any>
.
Any way to decode JSON value to PropertyWrapper
property?
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
}
let jsonData = jsonString.data(using: .utf8)!
let user = try! JSONDecoder().decode(People.self, from: jsonData)
print(user.name)
print(user.age)