Protocol-Oriented Programming is a design pattern that enables you to abstract implementation details across various components of your app. It’s commonly used to separate concerns in your code, such as decoupling UI logic from data logic.
For example, you might have a View to display a list of books. The view shouldn’t care about how the items are retrieved or whether it needs to make specific API calls or database queries to get the data. Instead, you can define a protocol:
This protocol outlines a few functions for retrieving and creating books Note how there are no implementation details; that’s decided by the implementer of the protocol. The view simply uses the protocol’s API to perform the actions it needs to.
This also makes it very easy to change the implementation; for example, you can easily switch between using SwiftData and an API or even some mocked data for testing.
You could then provide an implementation of this protocol that uses an API:
Defines a new type that conforms to BookRepository to retrieve books from an API.
Implements getBooks() to retrieve books from the API.
Uses URLSession to retrieve the data from the API and decode the response to an array of Books. The function must return this information.
Implements createBook(_:) to create a new book.
Encodes the book to JSON.
Creates a URLRequest to send to the API. Sets the method, header and body parameters for sending the new book data to the API.
Sends the request to the API using URLSession.
Note: For most SwiftUI apps, the responsibility of retrieving data is usually handled by a ViewModel rather than the View directly. The View’s sole responsibility is to display the data it receives. For more information, check out Advanced iOS App Architecture and other related Kodeco articles on the Model-View-ViewModel (MVVM) pattern.
See forum comments
This content was released on Oct 17 2023. The official support period is 6-months
from this date.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.