Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define variable with type of Codable?

I want to create variable with type of Codable. And later to use it in the JSONEncoder class. I thought that code from below should work fine, but it gives me error:

Cannot invoke encode with an argument list of type (Codable).

How to declare codable variable that JSONEncoder will be taking without error?

struct Me: Codable {
    let id: Int
    let name: String
}

var codable: Codable? // It must be generic type, but not Me.

codable = Me(id: 1, name: "Kobra")

let data = try? JSONEncoder().encode(codable!)

Here is similar question how to pass Codable using function. But I am looking how to set Codable using variable (class variable).

like image 419
Ramis Avatar asked Oct 04 '17 12:10

Ramis


1 Answers

Your code is all right, the only thing we need to focus is Codable.

Codable is a typealias which won't give you generic type.

JSONEncoder().encode(Generic confirming to Encodable).

So, i modified the code as below, it may help you..

protocol Codability: Codable {}

extension Codability {
    typealias T = Self
    func encode() -> Data? {
        return try? JSONEncoder().encode(self)
    }

    static func decode(data: Data) -> T? {
        return try? JSONDecoder().decode(T.self, from: data)
    }
}

struct Me: Codability
{
    let id: Int
    let name: String
}

struct You: Codability
{
    let id: Int
    let name: String
}

class ViewController: UIViewController
{
    override func viewDidLoad()
    {
        var codable: Codability
        codable = Me(id: 1, name: "Kobra")
        let data1 = codable.encode()

    codable = You(id: 2, name: "Kobra")
    let data2 = codable.encode()
}
}
like image 112
Deepak Avatar answered Oct 10 '22 03:10

Deepak