类型已经符合Encodable协议

问题描述 投票:0回答: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。同样的问题。我做错了什么?

错误:实例方法'encodeIfPresent(_:forKey :)'要求'[RelatedQuestions] .Type'符合'Encodable'我已经符合Codable协议的对象,但它仍在提供...

swift protocols codable encodable
1个回答
3
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.