Swift Codable手动解码可选变量 [英] Swift Codable Decode Manually Optional Variable

查看:86
本文介绍了Swift Codable手动解码可选变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

import Foundation

let jsonData = """
[
    {"firstname": "Tom", "lastname": "Smith", "age": "28"},
    {"firstname": "Bob", "lastname": "Smith"}
]
""".data(using: .utf8)!

struct Person: Codable {
    let firstName, lastName: String
    let age: String?

    enum CodingKeys : String, CodingKey {
        case firstName = "firstname"
        case lastName = "lastname"
        case age
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        firstName = try values.decode(String.self, forKey: .firstName)
        lastName = try values.decode(String.self, forKey: .lastName)
        age = try values.decode(String.self, forKey: .age)
    }

}

let decoded = try JSONDecoder().decode([Person].self, from: jsonData)
print(decoded)

问题在于 age = try values.decode(String.self,forKey:.age)。当我使用该 init 函数时,它可以正常工作。错误为没有与键龄(\ age\)相关的值。

Problem is it's crashing on age = try values.decode(String.self, forKey: .age). When I take that init function out it works fine. The error is No value associated with key age (\"age\")..

任何想法关于如何使该可选对象不存在时崩溃?出于其他原因,我还需要 init 函数,但仅举了一个简单的示例来说明发生了什么。

Any ideas on how to make that optional and not have it crash when it doesn't exist? I also need that init function for other reasons, but just made a simple example to explain what is going on.

推荐答案

年龄是可选的:

let age: String? 

因此,尝试以这种方式进行解码:

So try to decode in this way:

let age: String? = try values.decodeIfPresent(String.self, forKey: .age)

这篇关于Swift Codable手动解码可选变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆