Understanding Type Erasure in 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:
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.