1

错误:

实例方法 'encodeIfPresent(_:forKey:)' 要求 '[RelatedQuestions].Type' 符合 'Encodable'

我拥有的对象已经符合Codable协议,但它仍然给我它不符合的错误。为什么?

func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey: .id)
        try container.encode(date, forKey: .date)
        try container.encode(imgURL, forKey: .imgURL)
        try container.encode(thumbnail, forKey: .thumbnail)
        try container.encode(title, forKey: .title)
        try container.encodeIfPresent(tweetText, forKey: .tweetText)
        try container.encode(content, forKey: .content)

        try container.encode(isDailyHidden, forKey: .isDailyHidden)
        try container.encodeIfPresent([Wisdom], forKey: .wisdom) //ERROR
        try container.encodeIfPresent(churchFather, forKey: .churchFather)
        try container.encodeIfPresent(popeSay, forKey: .popeSay)
        try container.encodeIfPresent([RelatedQuestions], forKey: .relatedIds) //ERROR
        try container.encodeIfPresent([Video], forKey: .video) // ERROR
}

这是符合的模型之一Codable

struct RelatedQuestions: Codable {
    let id: String
    let number, title, imgUrl, thumbnail: String

    enum CodingKeys: String, CodingKey {
        case id, number, title, thumbnail
        case imgUrl = "img_url"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        title = try container.decode(String.self, forKey: .title)
        number = try container.decode(String.self, forKey: .number)
        imgUrl = try container.decode(String.self, forKey: .imgUrl)
        id = try container.decode(String.self, forKey: .id)
        thumbnail = try container.decode(String.self, forKey: .thumbnail)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey: .id)
        try container.encode(title, forKey: .title)
        try container.encode(number, forKey: .number)
        try container.encode(imgUrl, forKey: .imgUrl)
        try container.encode(thumbnail, forKey: .thumbnail)

    }
}

我清理了构建文件夹重新启动了 Xcode。同样的问题。我做错了什么??

4

1 回答 1

3

我懂了。这对您来说是一个明显的错字。

[RelatedQuestions]是一种类型。这不是要编码的东西。您必须使用实际的局部变量,例如self.relatedQuestions.

另请注意,您的解码和编码功能相当简单,可以自动生成,例如:

struct RelatedQuestions: Codable {
   let id: String
   let number, title, imgUrl, thumbnail: String

   private enum CodingKeys: String, CodingKey {
      case id, number, title, thumbnail
      case imgUrl = "img_url"
   }
}

实际上,甚至CodingKeys可以自动生成。

于 2020-04-15T16:14:26.373 回答