如何手动对选定的按键进行解码,以及如何使用快速的Decodable自动解码? [英] How to Decode selected keys manually and rest with the automatic decoding with swift Decodable?
问题描述
这是我正在使用的代码,
Here is the code I am using,
struct CreatePostResponseModel : Codable{
var transcodeId:String?
var id:String = ""
enum TopLevelCodingKeys: String, CodingKey {
case _transcode = "_transcode"
case _transcoder = "_transcoder"
}
enum CodingKeys:String, CodingKey{
case id = "_id"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: TopLevelCodingKeys.self)
if let transcodeId = try container.decodeIfPresent(String.self, forKey: ._transcode) {
self.transcodeId = transcodeId
}else if let transcodeId = try container.decodeIfPresent(String.self, forKey: ._transcoder) {
self.transcodeId = transcodeId
}
}
}
在这里,transcodeId
由_transcode
或_transcoder
决定.
但我希望id
和其余键(此处未包括)能够自动解码.我该怎么办?
Here, transcodeId
is decided by either _transcode
or _transcoder
.
But I want id
and rest of the keys (not included here) to be automatically decoded. How can I do it ?
推荐答案
由编译器生成的init(from:)
是全有还是全无.您不能让它解码某些密钥,而不能手动"解码其他密钥.
The compiler-generated init(from:)
is all-or-nothing. You can’t have it decode some keys and "manually" decode others.
使用编译器生成的init(from:)
的一种方法是给struct
和两者提供可能的编码属性,并使transcodeId
为计算属性:
One way to use the compiler-generated init(from:)
is by giving your struct
both of the possible encoded properties, and make transcodeId
a computed property:
struct CreatePostResponseModel: Codable {
var transcodeId: String? {
get { _transcode ?? _transcoder }
set { _transcode = newValue; _transcoder = nil }
}
var _transcode: String? = nil
var _transcoder: String? = nil
var id: String = ""
// other properties
}
这篇关于如何手动对选定的按键进行解码,以及如何使用快速的Decodable自动解码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!