类型需要符合 Encodable 协议,即使它已经是

Type needs to conform to Encodable protocol even though it is already

错误:

Instance method 'encodeIfPresent(_:forKey:)' requires that '[RelatedQuestions].Type' conform to '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。同样的问题。我做错了什么??

哦,我明白了。这是你这边明显的错字。

[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都可以自动生成