小编Wah*_*don的帖子

在 swift 中使用“默认值”创建非可选 Codable 的最佳方法

我知道classand的基本概念,struct但是为 API 创建模型以获取数据并告诉我优缺点更有效。

以前我不使用可选的模型。相反,我给了它一些价值。IE

class CompanyInfo : Codable {
    var NameEn : String = ""
    var CityEn : String = ""
    var Website : String = ""
    var Email : String = ""
    var Phone : String = ""
    var Fax : String = ""
}
Run Code Online (Sandbox Code Playgroud)

但是当它null从 API获得一些价值时。即"Fax": null然后应用程序崩溃,因为它无法使用以下行解析数据

let data = try JSONDecoder().decode(dataModel.self, from: dataSet)
Run Code Online (Sandbox Code Playgroud)

定义模型的最佳方法是什么,这样我就不需要解开可选项或给它默认值。

xcode ios swift codable decodable

2
推荐指数
1
解决办法
890
查看次数

标签 统计

codable ×1

decodable ×1

ios ×1

swift ×1

xcode ×1