[英]My structure does not conform to protocol 'Decodable' / 'Encodable' if I use protocol type in my structure in swift
在這里,我試圖從 json 文件中讀取數據,並動態轉換它。 但是,如果我在結構中使用原型,則表明我does not conform to protocol 'Decodable' / 'Encodable'
錯誤。 如果我在這里遺漏了什么,請告訴我。
struct ScreenData: Codable {
var id: String
var objectid : String
var config : UIConfig
}
protocol UIConfig: class, Codable{
var bgColor : String? { get set }
}
class LabelConfig : UIConfig {
var bgColor: String?
var label : String? = ""
}
class ButtonConfig : UIConfig {
var bgColor: String?
var btn_label : String = ""
//var btn_text_color : UIColor = .black
}
在這里,我正在從 json 文件中讀取數據,並根據數據在堆棧視圖中添加組件
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create stack view to add components
let stackView = UIStackView()
stackView.axis = NSLayoutConstraint.Axis.vertical
stackView.distribution = .fill
stackView.alignment = .fill
stackView.spacing = 10
stackView.backgroundColor = .gray
var screenData = [ScreenData]()
// read components from json
screenData = loadScreen()
//print("viewDidLoad screenData : \(screenData)")
for data in screenData {
let subView = loadScreenView(data: data, objectId: data.objectid)
//add components in stack view
stackView.addArrangedSubview(subView)
}
self.view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 10).isActive = true
stackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 10).isActive = true
stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
stackView.heightAnchor.constraint(equalToConstant: 200).isActive = true
}
// function to laod data from json
func loadScreen() -> [ScreenData] {
var jsonData = [ScreenData]()
if let fileLocation = Bundle.main.url(forResource: "screen_data", withExtension: "json"){
do{
let data = try Data(contentsOf: fileLocation)
let jsonDecoder = JSONDecoder()
let dataFromJson = try jsonDecoder.decode([ScreenData].self, from: data)
jsonData = dataFromJson
}catch{
print(error)
}
}
//print("loadScreen screenData :: \(jsonData)")
return jsonData
}
Here I check the object type, and depending on that cast the config
func loadScreenView(data : ScreenData,objectId : String) -> UIView {
var view = UIView()
if(objectId == "bd_label"){
print("bd_label")
let labelView = UILabel()
//labelView.sizeToFit()
let config = data.config as! LabelConfig
labelView.text = config.label
labelView.widthAnchor.constraint(equalToConstant: 300).isActive = true
labelView.heightAnchor.constraint(equalToConstant: 35).isActive = true
view = labelView
}
if(objectId.elementsEqual("bd_button")){
print("bd_button")
let buttonView = UIButton()
let config = data.config as! ButtonConfig
buttonView.setTitle(config.btn_label, for:.normal)
buttonView.backgroundColor = .blue
buttonView.widthAnchor.constraint(equalToConstant: 200).isActive = true
buttonView.heightAnchor.constraint(equalToConstant: 35).isActive = true
view = buttonView
}
if(objectId == "bd_input"){
print("bd_input")
let inputView = UITextView()
let config = data.config as! InputConfig
inputView.text = config.placeholder
inputView.backgroundColor = .white
inputView.widthAnchor.constraint(equalToConstant: 300).isActive = true
inputView.heightAnchor.constraint(equalToConstant: 35).isActive = true
view = inputView
}
return view
}
}
JSONDecoder
需要知道要將 JSON 解碼為的具體類型。 畢竟,一切都必須在運行時具有具體類型,您可以使用type(of:)
獲得。 你不能告訴它只是“解碼協議”。 編碼器有點不同 - 它實際上不需要知道具體類型,並且有一種方法可以繞過它。
看起來UIConfig
的類型取決於objectid
,所以我們可以檢查objectid
並決定要解碼的UIConfig
類型:
enum CodingKeys: CodingKey {
case id, objectid, config
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
objectid = try container.decode(String.self, forKey: .objectid)
if objectid == "bd_label" {
config = try container.decode(LabelConfig.self, forKey: .config)
} else if objectid == "bd_button" {
config = try container.decode(ButtonConfig.self, forKey: .config)
}
// other cases...
else {
throw DecodingError.dataCorruptedError(forKey: .config, in: container, debugDescription: "no suitable config type found for objectid \(objectid)!")
}
}
對於Encodable
部分,您可以制作類似“類型橡皮擦”的東西:
struct AnyEncodable: Encodable {
let encodeFunction: (Encoder) throws -> Void
init(_ encodable: Encodable) {
encodeFunction = encodable.encode(to:)
}
func encode(to encoder: Encoder) throws {
try encodeFunction(encoder)
}
}
並做:
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(objectid, forKey: .objectid)
try container.encode(AnyEncodable(config), forKey: .config)
}
通過使用AnyEncodable
,我們基本上將協議包裝在一個具體的類型中,但不用擔心 - 這實際上不會在 JSON 中創建一對額外的花括號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.