Tips for Writing Cleaner SwiftUI code

Uplift iOS Interview

The Guide is for YOU if
  • You are preparing for an iOS interview and want to improve your skills and knowledge and looking to level up your interview game and land your dream job.
  • You want to gain confidence and ease during iOS interviews by learning expert tips and curated strategies.
  • You want access to a comprehensive list of iOS interview QA to practice and prepare.

Welcome to this blog post on tips for writing better SwiftUI code! In this post, we will share some best practices and techniques that you can use to improve the quality, efficiency, and readability of your SwiftUI code. Writing clean code is important for any programmer working in a professional setting, regardless of the size or scope of the project. Clean code not only helps to improve the quality and reliability of the software, but it also makes it easier for others (or even yourself, after a period of time) to read and understand. The exact definition of clean code may vary, but a common theme is that it should be readable and easy to understand. By focusing on writing clean code, you can help to ensure that your software is maintainable, scalable, and of high quality.

The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that.

Robert C. Martin

Best practices

There are several best practices to consider when coding user interfaces and views in SwiftUI. First, focus on functionality rather than appearance, and try to keep your views as simple and modular as possible. You can also use semantic colors to convey meaning and context to your users, and consider how your views will be used on different platforms and devices. By following these practices, you can help to create user interfaces that are efficient, maintainable, and easy to use.

When coding user interfaces in SwiftUI, it is important to focus on functionality rather than appearance. This means that you should aim to create views that are simple, modular, and easy to use, rather than trying to make them look a certain way or match a particular aesthetic. By focusing on functionality, you can create user interfaces that are more efficient, maintainable, and scalable, and that are better able to meet the needs of your users.

There are several ways to focus on functionality when coding in SwiftUI. One approach is to use view composition to build your interfaces from smaller, reusable pieces, rather than trying to create everything from scratch. This can help to reduce duplication and make your code easier to maintain. You can also use protocols and other abstractions to make your views more flexible and adaptable, and to better support code reuse. Finally, you can use semantic colors and other design elements to convey meaning and context to your users, rather than just trying to make your views look a certain way. By following these principles, you can create user interfaces that are more effective, efficient, and easy to use.

In SwiftUI, views are extremely lightweight and efficient, as they are implemented as structs rather than classes. This means that there is little to no performance penalty involved in creating and manipulating views, and that you can create as many distinct and specialized views as you need for your app. Unlike UIViews in UIKit, which are dynamically subclassed and involve many memory allocations, SwiftUI views are composited together and only need to be rerendered if their state changes. This makes it easier and more efficient to create and manage complex view hierarchies, and to update your user interface in response to user input or data changes.

One of the key benefits of SwiftUI is that it allows you to use the same code across multiple platforms, including iOS, iPadOS, macOS, and tvOS. This makes it easier than ever to create consistent and seamless user experiences across devices, and to take advantage of the unique features and capabilities of each platform. When designing your user interface, it is important to consider how you can reuse your content views and navigation structures across different platforms, and to use SwiftUI’s mechanisms for specifying fonts, colors, and other design elements. By doing so, you can create user interfaces that are flexible, scalable, and easy to maintain.

One key to writing better SwiftUI code is to break large methods and functions into smaller ones. This has several benefits, including increased readability and understandability, self-documenting code (if function names are chosen well), and increased code reuse. It is generally a good idea to keep functions to less than 15 lines of code, and to limit arguments to three or fewer. Additionally, each function should do one thing and do it well, and avoid using “and” in the function name.

Another important aspect of writing better SwiftUI code is to constantly refactor and clean up your code. All too often, we write bad or inefficient code due to laziness, tight deadlines, or other factors, and then neglect to go back and fix it later. This can lead to code that is harder to maintain and more prone to bugs, and can also make it more difficult to add new features or fix issues. To avoid these problems, it is important to make refactoring a regular part of your workflow, and to allocate time and resources specifically for this task.

Key tips

Protocols to simplify SwiftUI views

Use protocols to simplify SwiftUI. Protocols are an important feature of Swift that allow you to define a set of requirements that a conforming type must fulfill. In SwiftUI, you can use protocols to simplify your code and improve the flexibility and reuse of your views.For example, suppose you have a simple SwiftUI view that displays a list of items:

struct ItemListView: View {
    var items: [Item]

    var body: some View {
        List(items) { item in
            Text(item.name)
        }
    }
}

This view works fine as-is, but it has a couple of issues that could be improved. First, it is not very flexible, as it can only display a list of Item objects. Second, it is not very reusable, as you would need to copy and paste the entire view if you wanted to use it in a different context.

To address these issues, you can use a protocol to define a common interface for the items property, and to make the view more flexible and reusable. For example:

protocol ItemList {
    var items: [Item] { get }
}

struct ItemListView: View {
    var itemList: ItemList

    var body: some View {
        List(itemList.items) { item in
            Text(item.name)
        }
    }
}

Now, the ItemListView is more flexible, as it can accept any type that conforms to the ItemList protocol. This means that you can use it to display lists of any type of object, as long as they have an items property and implement the ItemList protocol.

To use the ItemListView, you can create a struct or class that conforms to the ItemList protocol, and pass an instance of that type to the view. For example:

struct MyItemList: ItemList {
    var items: [Item]
}

struct ContentView: View {
    var body: some View {
        ItemListView(itemList: MyItemList(items: [Item(name: "Item 1"), Item(name: "Item 2")]))
    }
}

This technique can be very useful for simplifying and organizing your SwiftUI

Private @State

Apple offers three options for managing state in our apps: @State, @ObservedObject, and @EnvironmentObject. The first, @State, is best for simple local properties. @ObservedObject is more suitable for complex properties or properties that are shared between views. Finally, @EnvironmentObject is intended for properties that may be indirectly shared by many views. To ensure that @State properties are only used within the local view, Apple recommends marking them as private.

Views as functions

Use views as functions of their state. One of the core principles of SwiftUI is that views should be a function of their state. This means that you should try to avoid using imperative code to update your views, and instead use declarative code that describes the desired outcome.

Reusable views

Use composable, modular, and reusable views. SwiftUI encourages the use of small, composable views that can be combined and reused in different contexts. By building your views in this way, you can improve the reusability and maintainability of your code.

Custom modifiers

Use custom modifiers to apply styles and behaviors. Custom modifiers are a powerful feature of SwiftUI that allow you to define reusable styles and behaviors that you can apply to your views. By using custom modifiers, you can avoid repeating the same code across multiple views, and you can make it easier to apply consistent styles to your app.

Adaptive padding

It may be tempting to always manually control padding to achieve a specific appearance, but using the padding() modifier without any parameters allows for adaptive padding. This means that the padding will automatically adjust based on the content and environment, without the need for additional code. For example, if the app is running on an iPad in a regular size class, the padding will be greater than if the app is in split view on the same device. Consider using adaptive padding to save time and make your app more dynamic.

Environment values

Use environment values to pass data and settings between views. Environment values are a global state management feature of SwiftUI that allow you to pass data and settings between views in your app. By using environment values, you can avoid passing data through long chains of views, and you can make it easier to update and customize the behavior of your app.

View preference

Use view preferences to share data between views. View preferences are a way to share data between views that are not directly connected in the view hierarchy. By using view preferences, you can avoid passing data through long chains of views, and you can make it easier to update and customize the behavior of your app.

View builders

Use view builders to create views dynamically. View builders are a powerful feature of SwiftUI that allow you to create views dynamically, based on data or other input. By using view builders, you can improve the efficiency and flexibility of your code, and you can make it easier to create dynamic and customizable views.

XCode Live preview

Xcode’s live preview feature is a useful tool for coding layouts, but it can sometimes become sluggish when you make many changes at once. Instead of constantly pausing and resuming the preview, use this handy keyboard shortcut to reload the preview window and resume live updates: Option-Cmd-P. This will come in handy for SwiftUI developers.

I hope these tips have been helpful, and that they will help you write better SwiftUI code. Thank you for reading!



✍️ Written by Ishtiak Ahmed

👉 Follow me on XLinkedIn



Get Ready to Shine: Mastering the iOS Interview




Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book.

If you know someone who would benefit from reading this article, please share it with them.