Understanding Type Erasure in Swift


Disclaimer: The code for this post has been taken from an amazing book from Mattt called Flight School Guide to Swift.

In order to understand Type Erasure let’s take a look at a simple example. Let’s say we have JSON that we want to decode. The JSON looks like the following:

"foo" : "Hello",
"bar" : 123

There is no concrete class for the above JSON since we don’t know how many key-value pairs will the JSON contain.

In Swift 4.0 we can try to use the JSONDecoder class as shown below:

But that is not going to work and you will be presented with this error in the console.

error: JSONPlayground.playground:53:37: error: type ‘Any’ does not conform to protocol ‘Decodable’let dictionary = try! JSONDecoder().decode([String:Any].self, from: json)

The problem is that the “Any” type does not conform to Decodable protocol. This is be obvious because then every type will be Decodable. But now the real question is that how can we solve this problem.

This is where we will use the Type Erasure method of Swift. We are going to create a wrapper type which will hide the actual type. We will call this wrapper type AnyDecodable similar to the already existing type AnyHashable.

After you have implemented AnyDecodable you can use it as shown below:

Happy coding!

If you have enjoyed the article and want to support me then please check out my Udemy courses below. Use the coupon code “SUMMER2018” to get discount on courses.

iOS Developer, speaker and educator. Top Udemy and LinkedIn instructor. Lead instructor at DigitalCrafts. https://www.udemy.com/user/mohammad-azam-2/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store