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).
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()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With