High Cohesion SwiftUI Code

It’s important

Steven Curtis
3 min readMay 1, 2023
Photo by Fas Khan on Unsplash

Cohesion is a principle of software design which refers to the degree to which elements within a module (or component). High cohesion is preferable and is associated with reusability, robustness and reliability and often correlates to loose coupling.

Wait, what? Let’s see some examples. What could possibly go wrong (let me know in the comments).

Before we start

Difficulty: Beginner | Easy | Normal | Challenging

This article has been developed using Xcode 14.2, and Swift 5.7.2

Prerequisites:

* You will be expected to be able to create a SwiftUI project

Terminology

Cohesion: the degree to which the elements inside a module belong together

A high cohesion example

We wish to describe high cohesion through the use of small, focussed views and view models which have well-defined tasks and communicate through well-designed interfaces.

The following example does not represent perfection (it’s not finished, and I’m not thrilled about how I inject the user to the view model) but it does give some idea about how high cohesion might apply to a `SwiftUI` project.

--

--