[英]Trying to make this class codable and decodable
試圖使此類可編碼和可解碼
import Foundation
class Attribute : Decodable {
struct Att: Decodable {
var number: Int16
var label: String
var comments: String
// Everything from here on is generated for you by the compiler
init(from decoder: Decoder) throws {
let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
number = try keyedContainer.decode(Int16.self, forKey: .number)
label = try keyedContainer.decode(String.self, forKey: .label)
comments = try keyedContainer.decode(String.self, forKey: .comments)
}
enum CodingKeys: String, CodingKey {
case number
case label
case comments
}
}
}
extension Attribute: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(number, forKey: .number)
try container.encode(label, forKey: .label)
try container.encode(comments, forKey: .comments)
}
}
我在這些線上有錯誤
try container.encode(number, forKey: .number)
try container.encode(label, forKey: .label)
try container.encode(comments, forKey: .comments)
與消息
使用未解決的標識符“數字”
使用未解決的標識符“標簽”
使用未解決的標識符“注釋”
我該如何解決?
為什么您有一個帶有嵌套struct
的空class
? 錯誤來自於以下事實:這些屬性是在Att
而不是Attribute
上定義的,因此在擴展Att
以符合Encodable
時需要對這些Attribute
進行編碼。
順便說一句,您沒有任何特殊的編碼/解碼,因此您不需要手動聲明編碼器/解碼器功能,編譯器可以為您合成它們。
class Attribute: Codable {
struct Att: Codable {
var number: Int16
var label: String
var comments: String
}
}
我可能錯過了一些東西,但是以下代碼應該可以工作,或者至少可以編譯:
class Attribute : Decodable {
var number: Int16
var label: String
var comments: String
// Everything from here on is generated for you by the compiler
required init(from decoder: Decoder) throws {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.