我遵循按预期工作的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'不符合协议'可解码'
有没有办法不使用某些属性作为Codable?
我知道问题是 CMTime 和任何我不知道如何解决它
我搜索了很多问题,但是所有属性都来自API,没有找到自定义属性任何人都建议我任何解决方案或替代方式?
答案 0 :(得分:3)
如果您不想解码这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"
}
}
答案 1 :(得分:0)
首先从struct类型更改为class。添加不符合Codable协议的父类,例如VideoAlbumStatus并添加这些自定义属性。现在只继承父类。
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
}