Before starting developing our sections, I need to resolve one problem. From the screenshot, you can see that in different sections we have different objects and they have a different layout. With UICollectionViewDiffableDataSource we can’t do that, that’s why I will build a wrapper and it will help us.

I want to use just structures, this will be a small experiment for me, with them it will be easier to implement a Hashable protocol, but harder to store them.

Section & Cell

For a start let’s create two basic objects for our application. First will be a simple protocol Cell, this protocol will be implemented by our collection view cells. Inside it will have only one function, this function will be called by section and will configure a cell. Also, it will have an associatedtype Object, which will be passed in that function.

Second object is an abstract class Section, it will implement a Hashable protocol and this class helps us to have the common behavior for all future sections.

CollectionAdapter

CollectionAdapter is a class, it will handle our two crucial objects UICollectionViewCompositionalLayout and UICollectionViewDiffableDataSource. This adapter will store UICollectionViewDiffableDataSource and will ask for snapshots data from its delegate. As we decided in sections, we will have different elements, that’s why will use the AnyHashable structure.

The delegate will have two simple methods, the first will return all sections to our collection, second will return elements for the section. Section will provide cells for the data source, that’s why we should add a function to it.

Working with UICollectionViewCompositionalLayout is much more simple, all we have to provide is how elements will layout in the sections. In order to do this, the section must have an additional function that will return this information.

One more important function we must add to our adapter is the one that will create snapshots and send them to the datasource using the apply method. Also before that, it must register cells in a collection. ViewController will be the delegate for our adapter and will return al thel needed data. Below you can find the code for this function.

CollectionSection

I have decided that in one section I will have only one kind of elements. With this let me introduce to you a generic section class which I will use for sections — CollectionSection. This class will have two generic elements, first will be our element and second — a cell for it. This class will inherit from the Section class and will return cells and layout for our adapter.

Client Section

Regarding our requirements in this section we should have short information about the client and amount of books he has taken. So we need a cell and a model.

After this we should configure our new section and return data for it from ViewController to the adapter.