Photo by panumas nikhomkhai from Pexels

Clean Architecture: Core Data and Swift

Paul Allies
2 min readOct 19, 2021

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:

├─Core
└─Data
├─DataSource
│ ├── TodoDataSource.swift
│ └─CoreData
│ ├── Main.xcdatamodeld
│ └── TodoCoreDataSourceImpl.swift
└─Repository
└── TodoRepositoryImpl.swift

├─Presentation
└─Domain
├─Model
│ └── Todo.swift
├─Error
│ └── TodoError.swift
└─Repository
└── 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.

Domain/Model/Todo.swift

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

Data/DataSource/TodoDataSource.swift

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:

Data/DataSource/CoreData/Main.xcdatamodeld

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:

Domain/Repository/TodoRepository.swift
Domain/Error/TodoError.swift

--

--