0

In my code I have a class with a property of type [String: Any]. On implementing the Codable protocol the compiler shows error that says

Protocol type 'Any' cannot conform to 'Decodable' because only concrete types can conform to protocols

open class MMSDKNotification: Codable {

    enum MMSDKNotificationKeys: String, CodingKey { // declaring our keys
        case id = "id"
        case message = "message"
        case isRead = "isRead"
        case creationTime = "creationTime"
    }

    public var id: Int = 0
    public var message: [String: Any]?
    public var isRead: Bool = false
    public var creationTime: Int = 0

    required public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: MMSDKNotificationKeys.self) // defining our (keyed) container

        self.id = try container.decode(Int.self, forKey: .id)

        // Here is the error:
        // Protocol type 'Any' cannot conform to 'Decodable' because only concrete types can conform to protocols

        self.message = try container.decode(String.self, forKey: .type)

        self.isRead = try container.decode(Bool.self, forKey: .isRead)
        self.creationTime = try container.decode(Int.self, forKey: .creationTime)

    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: MMSDKNotificationKeys.self)

        try container.encode(id, forKey: .id)
        try container.encode(isRead, forKey: .isRead)
        try container.encode(creationTime, forKey: .creationTime)
    }
}

Is it possible to use Codable with [String: Any] dictionary?

Evghenii Todorov
  • 637
  • 6
  • 15
  • Think about what it means to conform to `Codable`. Conforming to `Codable` implies that your class can be converted to and from JSON. How do you convert a `[String: Any]` into a JSON format? Or in other words, how do you convert an `Any` into JSON format? – Sweeper Feb 11 '20 at 14:51
  • 1
    You can't declare Any type in Codable,, just create message Model which conforms protocol Codable. – Sargis Terteryan Feb 11 '20 at 15:04

2 Answers2

2

Is it possible to use Codable with [String: Any] dictionary?

no, you can't with Codable but you can make this dictionary in a new model.

Replace

public var message: [String: Any]?

with

public var message: MessageModel?

struct MessageModel: Codable { }

Community
  • 1
  • 1
0

Is it possible to use Codable with [String: Any] dictionary?

No you can't with Codable you have to explicitly write the type that should conform to Codable otherwise go with SwiftyJSON/JSONSerialization

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87