Answer the question
In order to leave comments, you need to log in
How to make JSON from an Encodable of an arbitrary class?
There is a function in Swift 4:
func encode(item: Encodable) -> Data {
return JSONEncoder().encode(item)
}
Protocol type 'Encodable' cannot conform to 'Encodable' because only concrete types can conform to protocols
Answer the question
In order to leave comments, you need to log in
Yes, there is no method in Encoder that would accept an abstract Encodable, it needs a concrete type. Generics will help to achieve this by virtue of their implementation.
func encode<T: Encodable>(_ item: T) throws -> Data {
return try JSONEncoder().encode(item)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question