相关疑难解决方法(0)

使用Swift 4中的JSONDecoder,缺少的键可以使用默认值而不必是可选属性吗?

Swift 4添加了新Codable协议.当我使用JSONDecoder它似乎要求我的Codable类的所有非可选属性在JSON中有键或它会引发错误.

使我的类的每个属性都是可选的似乎是一个不必要的麻烦,因为我真正想要的是使用json中的值或默认值.(我不希望这个属性为零.)

有没有办法做到这一点?

class MyCodable: Codable {
    var name: String = "Default Appleseed"
}

func load(input: String) {
    do {
        if let data = input.data(using: .utf8) {
            let result = try JSONDecoder().decode(MyCodable.self, from: data)
            print("name: \(result.name)")
        }
    } catch  {
        print("error: \(error)")
        // `Error message: "Key not found when expecting non-optional type
        // String for coding key \"name\""`
    }
}

let goodInput = "{\"name\": \"Jonny Appleseed\" }"
let badInput = "{}"
load(input: goodInput) …
Run Code Online (Sandbox Code Playgroud)

json swift swift4 codable

88
推荐指数
5
解决办法
3万
查看次数

标签 统计

codable ×1

json ×1

swift ×1

swift4 ×1