Photo by panumas nikhomkhai from Pexels

Clean Architecture: Core Data and Swift

Paul Allies


Continuing with our clean architecture, let’s write a simple Todo CoreData Datasource in swift. Our applications repository method would use the DataSource, in this case, the TodoCoreDataSource. Here is the proposed files and their locations:

│ ├── TodoDataSource.swift
│ └─CoreData
│ ├── Main.xcdatamodeld
│ └── TodoCoreDataSourceImpl.swift
└── TodoRepositoryImpl.swift

│ └── Todo.swift
│ └── TodoError.swift
└── TodoRepository.swift

Let’s first specify our Domain Model and Repository. We need a domain model because we can’t always control what our data source model looks and operates like.


Mapping between these two models would need to take place in our data source.


This time around we need a persistence framework for our data source. Here we’re going to use Core Data to save your application’s permanent data for offline use.

Create a CoreData Model by adding a new file and choosing Core Data -> Data Model and creating at TodoCoreDataEntity:


To use the CoreData Main Model we can create a data source that conforms to the TodoDataSource and uses the NSPersitanceContainer.

and then lastly, our TodoRepositoryImpl would implement our TodoRepository and call our Datasource: