Type Erasure in Swift - Generic Data Source Delegates

updated 10 months ago; latest suggestion 9 months ago

This proposal has been withdrawn...

Type Erasure in Swift

Separation of concerns is something we should all definitely aim for, whatever the context of development might be. Now, data sources as a way to separate network and data fetching related concerns, are definitely a healthy practice and a pattern one should definitely promote.

View controller and data source communication works best leveraging delegation and enhancing code decoupling practices. Adding to this, it would definitely be great to have one single protocol all view controllers could comply to in order to grant communication with their data sources as a way to have data retrieved and served in way that's common to every single one of these two element tuples.

To achieve that, this protocol needs to be generically constrained, so the complying view controller reificates the type of elements its data source should work on. Now this raises an issue, since the data source would hold a reference to a generically constrained protocol compliant object, leading to:

error: protocol GenericallyConstrainedProtocol can only be used as a generic constraint because it has Self or associated type requirements

This can be solved through the usage of Type Erasure! This talk will focus on showing a practical use case of Type Erasure (with playground live coding) to solve a problem most developers will face sooner or later!

Here's a brief preview of what you may expect from the talk: [https://skillsmatter.com/skillscasts/10598-type-erasure-in-swift-generic-data-source]

Suggestions

  • Ed8b3fcf16c3bf26d8e604113849c7b940bd36a0?size=100x100 ed8b3fcf16c3bf26d8e604113849c7b940bd36a0 suggests 9 months ago

    Love this topic as I frequently ran into the same "trap" and I think everybody who starts working with Generics in Swift sooner or later runs into this issue. Would it be possible to also include a short part to explain the difference and the use cases of generics and protocols with associated types (PATs)?