The Proper Way to Structure Your SwiftUI Code: Introducing the Wrap Code Method



This content originally appeared on Level Up Coding – Medium and was authored by Emin Emini

From Chaos to Clarity: A Practical Guide to Structuring SwiftUI Code

Photo by We The Creators on Unsplash

Imagine this: You open an old SwiftUI project, and within moments, you’re lost in a labyrinth of unorganized code. Sounds familiar? Don’t worry — you’re not alone. Whether you’re a senior developer or just starting out, writing clean, maintainable code can be challenging.

If you’ve been coding for a while, chances are you’ve come across some messy projects — everything was all over the place, unorganized, and hard to maintain. Whether you’re continuing a project or starting fresh, a clean structure helps you stay productive and maintainable in the long run.

That’s why I’m excited to introduce you to a new way of structuring your SwiftUI code: The Wrap Code Method.

The ultimate recipe for clean and maintainable SwiftUI Code

What’s Wrap Code Method?

The Wrap Code Method is a simple yet effective approach to organizing your SwiftUI code in a clean and maintainable way. Inspired by the structure of a wrap (think burritos, tacos, gyros, or shawarma), this method categorizes different components of your code to make them easier to manage. By following a consistent pattern, you can keep your project neat, readable, and scalable.

Why Is This Method Important?

SwiftUI is a powerful framework, but its declarative nature means that even simple views can become cluttered if you’re not careful. As your views grow in complexity, it becomes easy to mix up state management, layout, modifiers, and functions, which can lead to a chaotic codebase.

It provides a structured way to handle this complexity. It separates your code into distinct sections, making it easy to understand and work with, even as your app evolves.

Why Wrap Code? Well, just like a wrap (the food), the idea is that you neatly fold all your code components together into something organized and delightful. Let’s break it down.

How Can It Help You?

1. Improves Readability: By organizing your code into clear sections, you can quickly understand what each part of your view does. This is especially useful when collaborating with other developers or revisiting your project after a break.

2. Enhances Maintainability: A well-structured codebase is easier to modify and debug. If you need to update a part of your UI, you’ll know exactly where to look.

3. Facilitates Reusability: With a clean and modular structure, you can easily reuse components in different parts of your project or even across multiple projects.

4. Reduces Errors: When your code is well-organized, you’re less likely to introduce bugs or overlook important parts. Clear separation of concerns also helps prevent unexpected interactions between different elements.

What’s in a Wrap?

Illustration Generated with OpenAI DALL-E

We all know what a wrap is: it’s like a burrito but packed with ingredients of your choice and then wrapped up for convenience. In code, we’re also wrapping everything neatly together.

Here’s how the secret ingredients breaks down:

  1. Tortilla — The outer shell that wraps your view (this is your View struct).
  2. Ingredients — The foundational elements like State, Environment, and Properties that make up the view.
  3. Fillings — The main content inside the tortilla (the body of your SwiftUI view).
  4. Sauces — Modifiers that add extra flavor (like .padding(), .background(), etc.).
  5. Extras — Helper functions and extensions that provide additional functionality.

How to Implement it?

  1. Tortilla (Main View Wrapper)
    This is your SwiftUI view struct. Everything in SwiftUI starts with a View struct, just like a wrap starts with the tortilla that holds everything together.
struct ContentView: View {
var body: some View {
// Your main layout goes here
}
}

The main view struct acts as the outer shell, wrapping everything inside.

2. Ingredients (State, Environment, Properties)
Inside the wrap, you have the “ingredients” that form its foundation. In SwiftUI, these are your State variables, Environment properties, and other dynamic data.

@State private var isToggled: Bool = false
@Environment(\.presentationMode) var presentationMode

Properties form the foundation and manage the view’s state and behavior.

3. Fillings (Body)
This is where the magic happens. The main content of your wrap — the SwiftUI body. Think of it like the chicken, beef, tofu or falafel of your wrap, without which, the wrap wouldn’t be a wrap.

// ...

var body: some View {
VStack {
wrapTitle
toggleSwitch
actionButton
}
.padding()
}

// ...

// MARK: - Fillings (Body Components)
extension ContentView {

var wrapTitle: some View {
Text("Hello, SwiftUI!")
.font(.largeTitle)
.padding()
}

var toggleSwitch: some View {
Toggle(isOn: $isToggled) {
Text("Toggle Option")
}
.padding()
}

var actionButton: some View {
Button(action: closeView) {
Text("Close")
}
}
}

The body is the core content of your view, similar to the protein in a wrap.

4. Sauces (Modifiers)
What makes a wrap taste even better? Sauces! In SwiftUI, modifiers are like sauces. You can apply them to fine-tune the appearance and behavior of your views.

.padding()
.background(Color.gray.opacity(0.2))
.cornerRadius(10)

Modifiers fine-tune the appearance and layout, just like sauces enhance the flavor

5. Extras (Helper Functions & Extensions)
What’s a good meal without sides like fries or a drink? Similarly, in SwiftUI, we often have helper functions or extensions that add additional functionality to our views.

func closeView() {
presentationMode.wrappedValue.dismiss()
}

Helper functions and extensions are the bonus touches, adding extra functionality where needed.

Final Look at the Wrap Code Method

Here’s the complete code for the Wrap Code Method, structured and organized for readability, maintainability, and scalability:

import SwiftUI

// MARK: - Tortilla (Main View Wrapper)
struct ContentView: View {

// MARK: - Ingredients (State, Environment, Properties)
@State private var isToggled: Bool = false
@Environment(\.presentationMode) var presentationMode

// MARK: - Fillings (Body)
var body: some View {
VStack {
wrapTitle
toggleSwitch
actionButton
}
// MARK: - Sauces (Modifiers)
.background(Color.gray.opacity(0.2))
.cornerRadius(10)
.padding()
}
}

// MARK: - Fillings (Body Components)
extension ContentView {

var wrapTitle: some View {
Text("Hello, SwiftUI!")
.font(.largeTitle)
.padding()
}

var toggleSwitch: some View {
Toggle(isOn: $isToggled) {
Text("Toggle Option")
}
.padding()
}

var actionButton: some View {
Button(action: closeView) {
Text("Close")
}
}
}

// MARK: - Extras (Helper Functions)
extension ContentView {
func closeView() {
presentationMode.wrappedValue.dismiss()
}
}

// MARK: - Extras (Preview)
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

Give It a Try!

Implement this method in your next SwiftUI project and see how it transforms your workflow. Your future self (and your fellow developers) will thank you for having such clean, maintainable, and scalable code.

Happy coding, and enjoy your Wrap!

Hope this helped you, and you loved it. Also, sorry if I made you hungry 💙

If you want to see more articles like this, please make sure you clap it and share it 👏🏼.

Also, make sure you check these articles 👇🏻


The Proper Way to Structure Your SwiftUI Code: Introducing the Wrap Code Method was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding – Medium and was authored by Emin Emini