0

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)
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
William Hu
  • 15,423
  • 11
  • 100
  • 121
  • 2
    Swift can't synthesise a `Codable` implementation for you that also works with property wrappers (yet). You need to implement `Codable` by hand. – Sweeper May 13 '20 at 10:10

1 Answers1

0

Thanks to the comment, add this make it works.

extension People {
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)

        name = try values.decode(String.self, forKey: .name)
        age = try values.decode(Int.self, forKey: .age)
    }
}
William Hu
  • 15,423
  • 11
  • 100
  • 121