Understanding Type Erasure in Swift

https://fthmb.tqn.com/ihIH1sG3tiHx0rjlJYljOc9hW6g=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/erase-binary-data-yenwen-e-getty-images-56d054743df78cfb37b15127.jpg

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.

Like what you read? Give Mohammad Azam a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.