错误:
实例方法 '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。同样的问题。我做错了什么??