I want my strcut to conform to decodable, but I always get this error although i conformed to it.

Type 'DBTweet' does not conform to protocol 'Decodable'

That's my code:

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 {

    }
}

1 Answers

1
iDevid On Best Solutions

You haven't implemented the the init(from: Decoder). You can conform your models to Codable(Decodable) also without implement them if all of your model property conform to Codable to.

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]
}

Be sure that also DBUser, and DBComment conforms to Codable

[UPDATE] With 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)
    }
}