Тип должен соответствовать протоколу Encodable, хотя он уже - PullRequest
0 голосов
/ 15 апреля 2020

Ошибка:

Метод экземпляра '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. Та же проблема. Что я сделал не так?

1 Ответ

3 голосов
/ 15 апреля 2020

О, понятно. Это очевидная опечатка на вашей стороне.

[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 может быть сгенерирован автоматически.

...