Protocol types vs generics (or: encoding an Encodable)

Note that this has been discussed in other threads (namely, How to encode objects of unknown type?), and an implementation which does

func encode(to encoder: Encoder) throws {
    try value.encode(to: encoder)
}

won't quite give you what you want in all cases because it doesn't give an Encoder a chance to intercept the value before it encodes its contents. This is important for encoding strategies to apply (e.g. JSONEncoder.dateEncodingStrategy), which means that you could have inconsistent application of the strategy across your archive. @hamishknight's approach approach will more consistently give you the results you're looking for.

2 Likes