Home > Back-end >  Why don't conform Encodable protocol?
Why don't conform Encodable protocol?

Time:07-07

I try to convert Video object to the Dictionary !!!

So i find solution throught JSON. But it says - Type 'Video' does not conform to protocol 'Encodable'

So I try and failed. Help me please with this!

And if you know how to convert some type like Video to Dictionary without this, please tell it.

import Foundation
struct Video: Decodable, Encodable {    
    var videoId: String
    var title: String
    var numberOfViews: String
    var thumbnail: String
    enum CodingKeys: String, CodingKey {
        case snippet = "snippet"
        case thumbnails = "thumbnails"
        case high = "high"
        case statistics = "statistics"
        case videoId = "id"
        case title = "title"
        case numberOfViews = "viewCount"
        case thumbnail = "url"
    }
    init(from decoder: Decoder) throws {   
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let snippetContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .snippet)
        // Parse title
        self.title = try snippetContainer.decode(String.self, forKey: .title)
        // Parse thumbnails
        let thumbnailContainer = try snippetContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .thumbnails)
        let highContainer = try thumbnailContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .high)
        self.thumbnail = try highContainer.decode(String.self, forKey: .thumbnail)
        // Parse Video ID
        self.videoId = try container.decode(String.self, forKey: .videoId)
        // Parse numberOfViews
        let statisticsContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .statistics)
        self.numberOfViews = try statisticsContainer.decode(String.self, forKey: .numberOfViews)
    }
}

CodePudding user response:

enum CodingKeys is mapping custom fields that didn`t defined in properties

CodePudding user response:

Click on the error and then on Fix. Xcode will add encode(to:)

If you adopt both Decodable and Encodable and implement init(from:) you have to implement encode(to:), too.

  • Related