【问题标题】:Trying to make this class codable and decodable试图使这个类可编码和可解码
【发布时间】:2019-08-14 13:47:27
【问题描述】:

试图使这个类可编码和可解码

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)

与消息

使用未解析的标识符“数字”

使用未解析的标识符“标签”

使用未解析的标识符“cmets”

我该如何解决?

【问题讨论】:

  • extension Attribute.Att: Encodable 虽然我不明白你为什么将它嵌套在一个完全没有任何内容的类中......
  • 你能详细说明一下吗?我不明白你的意思。该类有 3 个属性。此类将用于编码为 Data 并通过网络传输到另一台计算机。
  • 类(可能是无意的)根本没有属性,struct 有...

标签: swift class swift4 codable decodable


【解决方案1】:

为什么你有一个空的class,里面有一个嵌套的struct?错误来自这些属性是在Att 而不是Attribute 上定义的,因此在扩展Att 以符合Encodable 时需要对这些属性进行编码。

顺便说一句,你没有任何特殊的编码/解码,所以你不需要手动声明编码器/解码器函数,编译器可以为你合成它们。

class Attribute: Codable {

    struct Att: Codable {
        var number: Int16
        var label: String
        var comments: String
    }
}

【讨论】:

  • 如果您的答案意味着将struct Att:Decodable 更改为codable,我这样做了,但错误仍然存​​在。你能发布你会如何做整个班级吗?谢谢。
  • 大卫已经解释了你的问题。 extension Attribute: Encodable 属性没有数字属性。 Attr 有(出于某种原因)
  • @SpaceDog 你可以在我的回答中看到所有相关代码
【解决方案2】:

我可能遗漏了一些东西,但以下应该可以工作,或者至少可以编译:

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 {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 2019-03-24
    相关资源
    最近更新 更多