为什么不符合协议encodable decodable?

Why not conform to protocol encodable decodable?

我有以下代码结构。如果我省略 codingkey 部分,则代码为 运行。我实现了 StringConverter 将字符串转换为 Int(来自 bySundell Swift Side)

struct Video: Codable {
    var title: String
    var description: String
    var url: URL
    var thumbnailImageURL: URL

    var numberOfLikes: Int {
        get { return likes.value }

    }

    private var likes: StringBacked<Int>
    enum CodingKeys: String, CodingKey{
        case title = "xxx"
        case description = "jjjj"
        case url = "url"
        case thumbnailImageURL = "jjjjjjjj"
        case numberofLikes = "jjjjjkkkk"

    }

}


// here the code for converting the likes
protocol StringRepresentable: CustomStringConvertible {
    init?(_ string: String)
}

extension Int: StringRepresentable {}
struct StringBacked<Value: StringRepresentable>: Codable {
    var value: Value

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let string = try container.decode(String.self)
        let stringToConvert = string.split(separator: "/").last!.description
        guard let value = Value(stringToConvert) else {
            throw DecodingError.dataCorruptedError(
                in: container,
                debugDescription: """
                Failed to convert an instance of \(Value.self) from "\(string)"
                """
            )
        }

        self.value = value
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(value.description)
    }}

正如我所说,如果我省略 Codingkeys 部分,它不会显示任何错误。我会简单地创建一个结构,我从 Rest API 中获取一个字符串,我想使用 Codable 为我的数据库转换一个 Int。 谢谢 阿诺德

定义CodingKeys时,需要为每个non-optional/non-initialized属性提供key,以便编译器在解码时知道如何初始化。将其应用于 Video,它看起来像这样,

struct Video: Codable {

    var title: String
    var description: String
    var url: URL
    var thumbnailImageURL: URL

    var numberOfLikes: Int {
        return likes.value

    }

    private var likes: StringBacked<Int>

    enum CodingKeys: String, CodingKey{
        case title = "xxx"
        case description = "jjjj"
        case url = "url"
        case thumbnailImageURL = "jjjjjjjj"
        case likes = "jjjjjkkkk"

    }
}

如果你仔细观察,这个 属性 private var likes: StringBacked<Int> 没有在枚举中提供任何 CodingKey 所以编译器在抱怨。我用这种情况 case likes = "jjjjjkkkk" 更新了枚举并删除了 case numberofLikes = "jjjjjkkkk" 因为 numberofLikes 是只读计算 属性 不需要任何解析。