R
R
redcircle2019-08-23 20:33:01
Swift
redcircle, 2019-08-23 20:33:01

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)
}

But the compiler throws an error
Protocol type 'Encodable' cannot conform to 'Encodable' because only concrete types can conform to protocols

How to implement similar functionality without using concrete classes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tapoton, 2019-08-25
@tapoton

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 question

Ask a Question

731 491 924 answers to any question