# How to encode objects of unknown type?

**URL:** <https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253>\
**Category:** Using Swift\
**Created:** [April 29, 2018, 11:40pm UTC](https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253 "2018-04-29T23:40:47Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![itaiferber](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/itaiferber/32/33840_2.png) [@itaiferber](https://forums.swift.org/u/itaiferber)\
**Post date:** [April 30, 2018, 7:37pm UTC](https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/6 "2018-04-30T19:37:15Z")

</div>

This is a clever implementation of `AnyEncodable`. Most implementations write

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

```

which is incorrect as it doesn't give the encoder the opportunity to intercept `value`'s type in order to apply things like encoding strategies. This actually ends up giving access to the inner type and preserving it correctly.

I guess this is the first implementation I've seen that I can largely endorse as Doing The Right Thing™. 😅

---

_[View the full topic](https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253)._
