我希望我的strcut符合可解码的要求,但是尽管我遵守,但我总是会收到此错误。
类型“ DBTweet”不符合协议“可解码”
那是我的代码:
struct DBTweet {
private(set) public var user: DBUser
private(set) public var profileImage: UIImage?
private(set) public var tweetID: Int
private(set) public var content: String
private(set) public var postedImageURL: String?
private(set) public var timestamp: String
private(set) public var comments: [DBComment]
}
extension DBTweet: Decodable {
enum MyStructKeys: String, CodingKey { // declaring our keys
case user, tweetID, content, postedImageURL, timestamp, comments
}
init(from decoder: Decoder) throws {
}
}
答案 0 :(得分:1)
您尚未实现init(来自:Decoder)。 如果所有模型属性都符合Codable,则也可以使模型符合Codable(Decodable),而无需实现它们。
struct DBTweet: Codable {
private(set) public var user: DBUser
private(set) public var profileImage: UIImage?
private(set) public var tweetID: Int
private(set) public var content: String
private(set) public var postedImageURL: String?
private(set) public var timestamp: String
private(set) public var comments: [DBComment]
}
确保DBUser和DBComment也符合Codable
[更新] 使用init:
struct DBTweet: Decodable {
private(set) public var user: DBUser
private(set) public var profileImage: UIImage?
private(set) public var tweetID: Int
private(set) public var content: String
private(set) public var postedImageURL: String?
private(set) public var timestamp: String
private(set) public var comments: [DBComment]
enum CodingKeys: String, CodingKey {
case user, tweetID, content, postedImageURL, timestamp, comments
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.user = try container.decode(DBUser.self, forKey: .user)
self.profileImage = nil // Construct here your profileImage
self.tweetID = try container.decode(Int.self, forKey: .tweetID)
self.content = try container.decode(String.self, forKey: .content)
self.postedImageURL = try container.decodeIfPresent(String.self, forKey: .postedImageURL)
self.timestamp = try container.decode(String.self, forKey: .timestamp)
self.comments = try container.decode([DBComment].self, forKey: .comments)
}
}