swift 为什么我的结构不符合可编码和可解码?

zfciruhq  于 2023-11-16  发布在  Swift
关注(0)|答案(1)|浏览(124)

下面是我用来解码JSON文件的结构体。Xcode给出了错误,并说它们不符合EncodableDecodable。这一个:

struct SocialModel: Codable {
    let id: Int
    let likeCount: Int
    let commentCounts: CommentCounts
    
    enum CodingKeys: String, CodingKey {
        case id
        case likeCount
        case commentCounts
    }
    
    init(id: Int, likeCount: Int, commentCounts: CommentCounts) {
        self.id = id
        self.likeCount = likeCount
        self.commentCounts = commentCounts
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decodeIfPresent(Int.self, forKey: .id) ?? 123
        likeCount = try container.decode(Int.self, forKey: .likeCount)
        commentCounts = try container.decode(CommentCounts.self, forKey: .commentCounts)
    }
}

struct CommentCounts: Codable {
    let averageRating, anonymousCommentsCount, memberCommentsCount: Int
}

字符串
还有这个

struct ProductModel: Codable {
    let productId: Int
    let name, desc: String
    let productImage: String
    let productPrice: Price
}

struct Price: Codable {
    let value: Int
    let currency: String
}


有谁能告诉我为什么吗?我试着做了很多次,但最后都没有成功。

k97glaaz

k97glaaz1#

你的结构体不符合可编码和可解码协议,因为你实现了自定义初始化器,这可能与Swift为可编码一致性提供的默认编码机制冲突。要使你的结构体符合可编码,你应该实现init(from:)和encode(to:)方法来指定你的自定义类型应该如何编码和解码。
下面是结构体的一个更新版本,包含了必要的init(from:)和encode(to:)方法:

struct SocialModel: Codable {
    let id: Int
    let likeCount: Int
    let commentCounts: CommentCounts

    enum CodingKeys: String, CodingKey {
        case id
        case likeCount
        case commentCounts
    }

    init(id: Int, likeCount: Int, commentCounts: CommentCounts) {
        self.id = id
        self.likeCount = likeCount
        self.commentCounts = commentCounts
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        likeCount = try container.decode(Int.self, forKey: .likeCount)
        commentCounts = try container.decode(CommentCounts.self, forKey: .commentCounts)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey: .id)
        try container.encode(likeCount, forKey: .likeCount)
        try container.encode(commentCounts, forKey: .commentCounts)
    }
}

struct CommentCounts: Codable {
    let averageRating, anonymousCommentsCount, memberCommentsCount: Int
}

struct ProductModel: Codable {
    let productId: Int
    let name, desc: String
    let productImage: String
    let productPrice: Price
}

struct Price: Codable {
    let value: Int
    let currency: String
}

字符串
通过在SocialModel结构体中实现encode(to:)方法,您可以提供有关如何对自定义类型进行编码的说明,使您的结构体符合Encodable协议。同样,SocialModel结构体中的init(from:)方法指定如何解码自定义类型,使您的结构体符合Decodable协议。

相关问题