[英]How to add custom transient property in Codable struct
我遵循了按预期工作的 Codable 结构
struct VideoAlbum: Codable {
let id, image: String?
let video, mediaType: JSONNull?
let type, deleted, createdOn: String?
let modifiedOn: JSONNull?
enum CodingKeys: String, CodingKey {
case id, image, video
case mediaType = "media_type"
case type, deleted
case createdOn = "created_on"
case modifiedOn = "modified_on"
}
}
// MARK: 编码/解码助手
class JSONNull: Codable {
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
现在我需要添加不是来自 API 的自定义属性来跟踪视频位置,所以我修改了它
struct VideoAlbum: Codable {
let id, image: String?
let video, mediaType: JSONNull?
let type, deleted, createdOn: String?
let modifiedOn: JSONNull?
var isPlaying:Bool? // CUSOTM PROPERTY
var currentTime:CMTime? // CUSOTM PROPERTY
var timeObserver:Any? // CUSOTM PROPERTY
var pausedByUser:Bool? // CUSOTM PROPERTY
enum CodingKeys: String, CodingKey {
case id, image, video
case mediaType = "media_type"
case type, deleted
case createdOn = "created_on"
case modifiedOn = "modified_on"
case isPlaying,pausedByUser
case currentTime
case timeObserver
}
}
然而它显示
错误类型“VideoAlbum”不符合“Decodable”协议
有没有办法不使用某些属性作为 Codable ?
我知道问题是与CMTime和任何我不知道如何解决它
我搜索了很多问题,但所有属性都来自 API,未找到自定义属性 有没有人建议我任何解决方案或替代方法?
如果您不想解码这 4 个属性,只需不要将它们包含在CodingKeys
(并且不要忘记为它们显式提供默认值,以便解码器可以正确初始化对象):
struct VideoAlbum: Codable {
let id, image: String?
let video, mediaType: JSONNull?
let type, deleted, createdOn: String?
let modifiedOn: JSONNull?
var isPlaying: Bool? = nil
var currentTime: CMTime? = nil
var timeObserver: Any? = nil
var pausedByUser: Bool? = nil
enum CodingKeys: String, CodingKey {
// include only those that you want to decode/encode
case id, image, video
case mediaType = "media_type"
case type, deleted
case createdOn = "created_on"
case modifiedOn = "modified_on"
}
}
首先从类型结构更改为类。 添加不符合 Codable 协议的父类,例如 VideoAlbumStatus 并添加这些自定义属性。 现在只需从父类继承 VideoAlbum。
class VideoAlbumStatus {
var isPlaying:Bool? // CUSOTM PROPERTY
var currentTime:CMTime? // CUSOTM PROPERTY
var timeObserver:Any? // CUSOTM PROPERTY
var pausedByUser:Bool? // CUSOTM PROPERTY
}
class VideoAlbum: VideoAlbumStatus, Codable {
let id, image: String?
let video, mediaType: JSONNull?
let type, deleted, createdOn: String?
let modifiedOn: JSONNull?
enum CodingKeys: String, CodingKey {
case id, image, video
case mediaType = "media_type"
case type, deleted
case createdOn = "created_on"
case modifiedOn = "modified_on"
}
//TO DO
// init() for VideoAlbum class
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.