【发布时间】:2019-02-25 19:06:19
【问题描述】:
我有以下一般结构,其中data 可以是任何其他可编码对象
struct GeneralResponse<T:Codable>: Codable {
let message: String
let status: Bool
let data: T?
enum CodingKeys: String, CodingKey {
case message = "Message"
case status = "Status"
case data = "Data"
}
}
我有 Follow Like 响应可编码类,将在 GeneralResponse 中用作 data
class ImgLike: Codable {
let id: Int?
let imageID, user: String?
@available(*, deprecated, message: "Do not use.")
private init() {
fatalError("Swift 4.1")
}
enum CodingKeys: String, CodingKey {
case id = "ID"
case imageID = "ImageID"
case user = "User"
}
}
问题 1 :当令牌在 API 上过期时,响应 data 仍为空 {} 仍然显示具有所有 nil 属性的 ImgLike 对象。为什么它不显示数据为零?
然后,如果我检查 object?.data == nil 它显示为 false !所以我需要检查每个属性
问题 2:在 ImgLike 如果我使用自定义编码功能。 GeneralResponse not parsed with ImgLike not parsed 它在 catch 语句中显示错误
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
imageID = try values.decode(String.self, forKey: .imageID)
user = try values.decode(String.self, forKey: .user)
do {
id = Int(try values.decode(String.self, forKey: .id))
} catch {
id = try values.decode(Int.self, forKey: .id)
}
}
【问题讨论】: