我想将 JSON 字符串解码People
为如下。age
is number( Int
) 类型,下面的代码出错:
"Expected to decode Dictionary<String, Any> but found a number instead."
我认为这意味着@Age
被视为Dictionary<String, Any>
.
有什么方法可以将 JSON 值解码为PropertyWrapper
属性?
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)