【问题标题】:Decode to PropertyWrapper from JSON从 JSON 解码到 PropertyWrapper
【发布时间】:2020-05-13 10:08:03
【问题描述】:

我想将 JSON 字符串解码为People,如下所示。 age 是 number(Int) 类型,下面的代码会报错:

"Expected to decode Dictionary<String, Any> but found a number instead."

我认为这意味着@Age 被视为Dictionary&lt;String, Any&gt;

有什么方法可以将 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)

【问题讨论】:

  • Swift 无法为您合成同样适用于属性包装器的 Codable 实现(目前)。你需要手动实现Codable

标签: swift codable property-wrapper


【解决方案1】:

感谢评论,添加它使其工作。

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)
    }
}

【讨论】:

    猜你喜欢
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多