【问题标题】:Cannot invoke 'decode' with an argument list of type '([[Notice]?])'无法使用“([[Notice]?])”类型的参数列表调用“解码”
【发布时间】:2019-08-05 05:25:23
【问题描述】:

当我确认可解码协议时,如何快速从解码器中解码列表

struct ActiveModuleRespones:Codable {
    var Notice:[Notice]?
    var Module:[Module]?


    public init(from: Decoder) throws {
        //decoding here
        let container = try from.singleValueContainer()
        self.Notice = try? container.decode([Notice].self)
    }

}

收到此错误:

Cannot invoke 'decode' with an argument list of type '([[Notice]?])'

截图:

请帮忙,

【问题讨论】:

  • 第一条规则 - 类、结构和枚举名称以大写字母开头。变量、方法和案例名称以小写字母开头。第二条规则 - 不要将变量命名为与类型名称完全相同。太多的混乱。修复这些问题,你的代码会更好。
  • 天哪!我遵循该规则,但仅在本课程中,我们得到NoticeModule 我将尝试使用自定义密钥(CodingKeys),非常感谢您的评论@rmaddy

标签: swift codable decodable


【解决方案1】:

它与变量本身混淆了。更改变量的名称以修复它。

struct ActiveModuleRespones: Codable {
    var notice: [Notice]?
    var module: [Module]?

    public init(from: Decoder) throws {
        //decoding here
        let container = try from.singleValueContainer()
        self.notice = try? container.decode([Notice].self)
    }
}

在 Swift 中,所有类型都有UpperCamelCase名称,几乎任何其他都有lowerCamelCase名称。

最后,使用try? 会杀死所有异常,你永远不会知道哪里出了问题,请尝试使用它:

self.notice = try container.decode([Notice]?.self)

【讨论】:

    【解决方案2】:

    如果您需要可选值,请使用带有非可选类型的 decodeIfPresent 而没有 try?

    struct ActiveModuleRespones: Decodable {
        var notice: [Notice]?
    
        enum CodingKeys: String, CodingKey {
           case notice
        }
    
        public init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            self.notice = try container.decodeIfPresent([Notice].self, forKey: .notice)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多