tezvyn:

Decoding a heterogeneous JSON array by a type field

Source: interviewintermediate

WHAT IT TESTS: custom Decodable with a discriminator. OUTLINE: peek the type field with a partial decode, switch on it, and decode the concrete type, wrapping each in an enum or boxed protocol value.

WHAT IT TESTS: comfort writing manual Decodable logic around a discriminator. ANSWER OUTLINE: decode the type field first using a small helper struct or by reading the discriminator key, switch on its value, and decode the matching concrete type; wrap each result either in an enum case or in a type-erased box so the array element type is concrete. You cannot decode straight into a bare protocol because protocols are not themselves Decodable. RED FLAG: declaring the array as [SomeProtocol] and expecting synthesized decoding to work.

Read the original → interview

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

Decoding a heterogeneous JSON array by a type field · Tezvyn