I perceive the Swift community as a very, very vivid and active one... the people really lean towards learning the bits and pieces, networking and in parallel giving talks, producing videos and writing blog posts - they invest just so much creative, mindblowing energy 🤯.
Well, and here am I copycating adopticating certain best practices based on other people's work...
Compared to other languages and SDKs I feel (especially with SwiftUI) there are maybe too many ways to structure and organize your projects in meaningful ways. This is especially true, when it comes to get a team with different experiences on the same page and into a productive flow.
Luckily there are a hell of a lot good, well tested and documented approaches that can help you out... but it seems like choosing the fitting ones, can be an art for itself.
With all the influences devs probably unavoidably end up with a mashup of things that form their architecture. In this post I am going to bisect Thomas Ricouard's IceCubes App in the version 1.10.32 and combine it with some other blog posts, to get my mashup of best practices and hopefully good ideas.
Overall this article will present various options, apply some selected parts for a real-world application, and review the descisions made. The article was written and partially extended throught 2024 and early 2025.
You can find a list of referenced authors and the cited articles directly in the sources section.
Disclaimer: Having prepared a bigger post, I'm aware that some techniques or fine-level aspect might already been outdated at the time of writing. As this post tries to establish a baseline for an App architecture there are things that you have to stick by, and some you can re-evaluate and refactor, depending on your time and commitment.
- Structuring - Anything is a package if you're brave enough
- A Central TabView
- MVVM - The thingy with the model
- Nitpicking - Extend and MARK
- Logging - Chopping some log
- Error Handling
- Injection - the with()-notation
- AppRouting - This is the way
- AppStorage
- Theming
- - 🤖 This chapter was AI-drafted based on manually created sourcecode. The draft was personally revised, manually changed in style, wording and compactness.
- Documentation
- Localization
- Previews
- Testing
- Clean Code
- Conclusion
- Sources
Structuring - Anything is a package if you're brave enough
For the sake of modularity and separation of concerns, it is a good idea to use (local) packages. This is also encouraged by Apple 2' 3' 4 and surely used by popular apps like Thomas Ricouard's IceCubes @ v.1.10.32 .
It is purely up to you, your team and the project's demands, where to draw the line 8 but for now I'd like to adopt Ricouard's App, Env, Model, Networking, Repository , Services and View and DesignSystems concept, as it — at least in the moment — suits my way of thinking and layering.
Though my poorly made graphic suggests a spaghetti architecture for my delicous mashup, this is somewhat of a layered approach with the following components:
-
App: top-level App binding everything together (see later chapter with()- notation). Depends on all lower layers and external dependencies. -
View(s): one of several packages withviewsandsubviews. Each view-package is responsible to show and modify data, as described by theModels. Does containViewModels. -
DesignSystems: Utilites, extensions and re-usable components adressing design issues. Might be on the same level like the views, might be below. -
Networking: if need be your networking happens here. You'll have to use theModels. -
Repository: -
Services: -
Env: GlobalEnvironment-related stuff such asRouting, storingPreferencesor Constants. -
Models: Domainmodel, maybe persistance models.
Arguebly the Networking packages can be swapped for indidvidual WebService implementations or omitted if your App does not need networking at all. It might even be, that used third-party libraries handle this layer's functionality already fair enough.
As we see later on, the routing needs to have the domain models in a (at least) neighbored layer. This can be somewhat of a downside if you rather like to package your view, viewModel and model together.
If the list of local packages in XCode (image below) annoys or irritates you, you can package erverything in a dedicate Library project like Majid did in his series "Microapps architecture in Swift. SPM basics."
A Central TabView
Most modern Apps rely on one principal TabView to present the App's views in an organized fashion. With iOS, iPad OS and VisionOS in mind IceCubes-App @ v.1.10.32 decides on the AppViews top-level, whether to show a TabBar or a SideBar.
The methodology to create and show the TabView is quite sophisticated, and relies on an enum of Tabs, their names and icons. Danijela Vrzan's Article Handle TabView data in a type-safe way with Enums explains the principal in a boiled down example with two tabs displayed in a enum with a String raw value13
enum Tab: String { case home case settings // Tab title var title: String { switch self { case .home: return "Home" case .settings: return "Settings" } } // Tab icon var icon: String { switch self { case .home: return "house" case .settings: return "gear" } } }
She uses a SceneStorage property to easily keep track of the selectedTab :
@SceneStorage("SelectedTab") private var selectedTab: Tab = .home ... TabView { HomeView() .tabItem {Label(Tab.home.title, systemImage: Tab.home.icon)} .tag(Tab.home)
Ricouard uses a more complex approach, as his App for one shows different Tabs based on the device and the state of the client. In essence his tab enum enum Tab: Int, Identifiable, Hashable, CaseIterable, Codable { allows him to hold more information and to iterate over all availableTabs :
ForEach(availableTabs) { tab in tab.makeContentView(selectedTab: $selectedTab, popToRootTab: $popToRootTab) .tabItem { if userPreferences.showiPhoneTabLabel { tab.label .environment(\.symbolVariants, tab == selectedTab ? .fill : .none) } else { Image(systemName: tab.iconName) } } .tag(tab) .badge(badgeFor(tab: tab)) .toolbarBackground(theme.primaryBackgroundColor.opacity(0.30), for: .tabBar) }
It is really charming to have the view creation pooled in the makeContentView() function but overall, I suggest that the App complexity dictates, which approach is more suitable for you. To be clear: in my opinion any App should at least implement Vrzan's way, as another implementation is just some refactoring away.
For my mashup I chose to pool the tab creation (pooled tab management) and to iterate over a not so elaborate Tab enum like this:
ForEach(iOSTabs.tabs, id: \.rawValue) { tab in tab.makeContentView(for: tab) .tabItem {Label(tab.title, systemImage: tab.icon)}.symbolRenderingMode(.hierarchical) .tag(tab) }
The other bits and pieces are part of an afterthougt as for the early stage of an App it feels like yagni 9 and need to be adressed as the code evolves. If needed, we know there is a boilerplate to look things up.
MVVM - The thingy with the model
Coming from UIKit and having sorts of a shell shock from the good old massive view controller, the community steered towards more maintainable patterns. One all-time favorite is also quite old Model-View-ViewModel or in short MVVM. Paul Hudson found a beautiful way to introduce MVVM to your views 12.
In essence he extends a given view with an @Observable ViewModel (in a dedicated file) and then adds the object as State property to the actual view.
ContentView+ViewModel.swift
extension ContentView { @Observable class ViewModel { ... } }
ContentView.swift
@State private var viewModel = ViewModel()
Hudson has even more tipps and warnings for implementing and integrating the ViewModel, so make sure to check out his article. Also be aware, that -depending on the ViewModel's complexity using the ObservedObjects property wrapper instead of State (@ObservedObject private var viewModel: ViewModel) could be beneficial. In a different article 14 Hudson hows how to initiate a State wrapped ViewModel in the View's initializer like so:
public init(modelContext: ModelContext) { let viewModel = ViewModel(modelContext: modelContext) _viewModel = State(initialValue: viewModel) }
Both approaches come with pros and cons and sometimes even side effects. Smaller ViewModels benefit from using the State property wrapper and tend to avoid concurrency problems. A SwiftData in the ViewModel integration (see below) worked with State but not with EnvironmentObject, whereas using the State on to complex ViewModels broke functionality. Key competeny could be knowing further information about which property wrapped to use when ( 15, 5).
Dataflow
In the context of dataflow Thomas Ricouard wrote an opinion piece on iOS Architecture. The piece boils down to
So, the next time you start a SwiftUI application, ask yourself which architecture you should use. Try a simple MVVM architecture, make small views, small view model, everything private, and use State, Published, Observed, and Observable objects. If you need something available to your whole app, make an EnvironmentObject and inject it at the app level. These are just a few examples.
But the mind opening part 🤯 was the call to watch and more importantly understand the WWDC Sessions WWDC19 Data Flow Through SwiftUI, WWDC20 Data Essentials in SwiftUI, WWDC21 Demystify SwiftUI .
My notes on that topic can be found here, but you really want to understand, who owns data that is presented and modified in views and how you can interweave views and models. Prior to my case study I was using the dependency injection framework "Factory" but lately I came to believe that that Ricouard's approach (EnvironmentObject on app level) is better suited.
Truth to be spoken, I always struggled with async data spilling in and modifiying the viewmodel. Also initializing the viemodel's inital loading was sometimes something unpleasent to deal with.
I really would love the ViewModel to initalise itself within the initializers 17, but often the exterior trigger from within .onAppear()18 method seems to be the way to go.
@Published var result = MyModel() init(obj: MyModel) { Task { let data = await fetchData() DispatchQueue.main.async { self.result = data } } }
vs.
var body: some View { List(viewModel.result.items) { item in } .onAppear { viewModel.fetchData() } }
MWWM and SwiftData
SwiftData can easily be embedded and used in any SwiftUI view. But from time to time it becomes necessary to process and filter data or perform simple statistics to enrich a view. Putting these operations into the view might often feasible, but does not promote a good readabiltiy.
In the article How to use MVVM to separate SwiftData from your views Hudson shows how to prepare the View initialiser to pass in the necessary ModelContext as ViewModel parameter.
public init(modelContext: ModelContext) { let viewModel = ViewModel(modelContext: modelContext) _viewModel = State(initialValue: viewModel) }
In the ViewModel itself you are free to fetch and add data
init(modelContext: ModelContext) { self.modelContext = modelContext fetchData() } func fetchData() { do { let descriptor = FetchDescriptor<MyModel>(sortBy: [SortDescriptor(\.name)]) models = try modelContext.fetch(descriptor) } catch { print("Fetch failed") } } func addData() { let model = MyModel(name: "Test") modelContext.insert(model) fetchData() }
In that context and in combination of asynchronous calls from the UI you'll encounter some problems if you choose not to use the State property wrapper for the ViewModel. These problems will depend on how you like to perform loading the data and where it stems from (SwiftData, exterior API calls).
- Synchronous as part of the ViewModels initialiser (shown above)
- Asynchrounous as part of an callable
setup()orfetchDatamethod.
I lean towards async fetches on apperance of a View if the data is loaded from exterior sources or loading takes quite long. Be aware, that some variants and combinations will simply break your code. Also: I recommend to not move the SwiftData data retrival into the ViewModel unless really necessary (processing). For example simply listing data without using a ViewModel is absolutely fine and counteracts over engineering.
Additional hint: If View A creates data that View B needs to display, calling modelContext.processPendingChanges() on apperance of View B worked wonders to have a common SwiftData state. Also the fetching the data should happen on an onAppear-context rather than at initialisation.
Handling Empty State - ContentUnavailabeView and Redaction
A good straightforward way to display empty or unloaded state is the ContentUnvailableView. Danijela Vrzan and Majid Jabrayilov show how you could .overlay the main component when data is simply not present, yet.
List(viewmodel.items, id: \.self) { item in Text(item) } .overlay { if viemodel.item.isEmpty { ContentUnavailableView("No data", systemImage: "circle") } }
Further infos can be found in the resepective articles Handle empty views in SwiftUI with ContentUnavailableView, Mastering ContentUnavailableView in SwiftUI/ or the video ContentUnavailableView in iOS 17.
Back in 2021 Peter Friese supposed implementing a view modifier [^pf:1] which could be used for other components, too.
Text("Hello, World!") .emptyState($isEmpty) { Text("Sorry - no content available") }
This is an approach that is also used in Steward Lynch's pretty informative ContentUnavailableView in iOS 17 video. In that tutorial you can find out how to deal with search bars and empty search results by means of the ContentUnvavailableView.
If you need to indicate misisng data in a already loaded View, using Apples .redacted method might just work fine, too.
Nitpicking - Extend and MARK
It is always a good idea to seperate your code and for that matter to split structs and classes in readable sections. So it is truely a no-brainer to use Swift extension and the pre-processor directive MARK for documentation 10.
For example IceCubes TimelineViewModel @ v.1.10.32 shows how the basic ViewModel is implemented and then extended for caching or later for status fetching.
// MARK: - Cache extension TimelineViewModel { ... }
Be like Thomas Ricouard and the others mark your work :-)
Logging - Chopping some log
A fine way of chopping your log with Swift is to create a Logger extension 116 like this:
import OSLog extension Logger { private static var subsystem = Bundle.main.bundleIdentifier! static let loggerA = Logger(subsystem: subsystem, category: "MyFirstLogger") static let loggerB = Logger(subsystem: subsystem, category: "MySecondLogger") } ...
You can easily create a plethora of loggers by setting categories. In order to use the logger to its full potential, be sure to make yourself familiar with the log levels or OSLogType .
Antoine van der Lee's article goes on by showing how to efficiently work with XCode to search the produced log for subsystems and categories. So does Steward Lynch in his video about Xcode Structured Logging. To quickly find my logged info, I used to trace my file or class as well as method with a notation like this MySpecialClass#myMethod: info about something special. A rather rudimentary approach, which was working for me as long as I did not refactor things to carless. After introducing the #file, #line and #function macros, Needles to poins out, that even those are in deed not needed anymore. Among other information, the XCode console shows the respective Call Site for each logging entry. Just select a line and press space. What great times we are living in.
Both sources also point out:
- You can right click an
jump to source. - You can filter for message types, subsystems and categories.
- You can always show inline information in the console (image below)
You could lookup aclima's Logging Etiquette to see which events can be deemed worthy (🔨⚡️) for logging and how to log and deal with errors. He also suggests using structured logging 17 logging style, which can be used by different logging backends.
// NOT structured logging style log.info("Accepted connection \(connection.id) from \(connection.peer), total: \(connections.count)")
vs. structured logging pattern,
log.info("Accepted connection", metadata: [ "connection.id": "\(connection.id)", "connection.peer": "\(connection.peer)", "connections.total": "\(connections.count)" ])
Simon B. Støvring suggest a simple, but powerful OSLog extension so you can quickly init your logger.
import OSLog extension Logger { init<T>(forType type: T.Type){ let subsystem = Bundle.main.bundleIdentifier! let category = String(describing: type) self.init(subsystem: subsystem, category: category) } } private var logger = Logger(forType: Self.self)
The disucssion under the OSLog extension post show different approaches, feel free to investigate.
Error Handling
- 🤖 This chapter was AI-drafted based on manually created sourcecode. The draft was personally revised, manually changed in style, wording and compactness.
Error handling is managed as usual with domain-specific error enums in the service layer and a catch-and-log pattern in the ViewModels.
Those enums vary depending on their layer — for example APIError with cases like requestError, decodingError, and networkError. A second, more localized error type exists in AppProgressError with cases like progressNotFound and saveFailed.
Due to the rigourous catching of errors, there are no LocalizedErrors that produce user-facing messages.
Whenever data is retreived or loaded the Result enumeration was used
enum Result<Success, Failure> where Failure : Error, Success : ~Copyable, Success : ~Escapable
The Result<_, _> Pattern
As shown before our data processing Serivces rely on Repositories to retreive data.
Occuring errors are propagated upwards after evaluating the Result<_, _> for .success or .failure.
private func handleRequest(query: MediaQuery) async throws -> DataList? { let result = await JSONDataRepository.shared.fetchData(for: query) switch result { case .success(let dataList): return dataList case .failure(let error): self.logger.error("Failed to fetch data: \(error)") throw error } }
The user-facing error processing is part of the respective ViewModels and Views. In conclusion one could say, that the presented error handling is basic and in parts incomplete (as it is for example not localized).
Injection - the with()-notation
With SwiftUI strongly using Command Chain Expression, you can pool recurring View injections and settings in a central manner. Ricouard does this with an AppRegistry, that offerswithXYZ-functions which extend aView.
@MainActor extension View { /// Add app navigation capabilities. func withAppRouter() -> some View { ... } /// Adds sheet destinations that can be shown. func withSheetDestinations(sheetDestinations: Binding<SheetDestination?>) -> some View { ... } /// Adds environment objects. func withEnvironments() -> some View { ... } /// Adds SwiftData storage capabilities. func withModelContainer() -> some View { ... } }
Whenever a View is instantiated and needs a certain capability, e.g. AppRouting for transitioning between Views or showing Sheets or SwiftData access, you'll simply append your withXYZ()-function.
ItemView() .withAppRouter() .withSheetDestinations(sheetDestinations: $routerPath.presentedSheet) .withModelContainer() .withEnvironment()
This appending approach can be an essential concept to tie everything together without using depdency injection. The with()-functions can surely be named with what ever works for your team. Maybe you are a little bit more of an adder (addXYZ) or an injecter (injectXYZ) , I truley don't judge 🤞.
AppRouting - This is the way
Central App routing
-
Env\Routing.swiftholds all possible routes and sheet destinations in a central manner.
/// Possible routes public enum RouterDestination: Hashable { case dashBoardView(id: String) } /// Possible sheets public enum SheetDestination: Identifiable { case addItemSheet public var id: String { switch self { case .addItemSheet: "addItemSheet" } }
The file provivdes a injectable RouterPath object
// Inject and use anywhere you have a NavigationStack @Observable public class RouterPath { public var path: [RouterDestination] = [] public var presentedSheet: SheetDestination? public init() {} public func navigate(to: RouterDestination) { path.append(to) } }
On the top level of your app you can instantiate the global router path and bind it to any subsequent View. This allows you to push views and present sheets on the top level of your application.
@main struct MyApp: App { @State var appRouterPath = RouterPath() ... var body: some Scene { MainView(appRouterPath: $appRouterPath) } ...
@MainActor struct MainView: View { @Binding var appRouterPath: RouterPath ...
That very method can also be used on any of the embeded Tabs (see chapter TabView) like follows:
@State private var routerPath = RouterPath() var body: some View { NavigationStack(path: $routerPath.path) { MyView() .withAppRouter() .withSheetDestinations(sheetDestinations: $routerPath.presentedSheet) .withModelContainer() .navigationTitle("MyView") .environment(routerPath) } }
And within the embedded view
public struct MyView: View { @Environment(RouterPath.self) private var routerPath public var body: some View { HStack { List(myObjects) { item in HStack { Text(item.label).font(.caption) } .onTapGesture { routerPath.navigate(to: .anotherView(param: item)) } } } }
It is essential to recognize, that this kind of navigation demands that Router knows the definition of the any passed argument, in this case item . To resolve this, you could use several workarounds based on native datatypes or protocols. I for my part will give this approach a go and see how it scales for my project.
AppStorage
Knowing the goold old UserDefaults there is a new kid in the town: AppStorage. The AppStorage can easily be used to store User- and App-preferences and to realise theming and font selection (see next chapter). Thomas Ricouard introduced a Singleton class UserPreferences with an internal Storage-class. The inner class is set to hold and initialise all AppStorage entries.
The outer class has offers namesake computed variables where the didSet manages a proper write to the persistent storage.
// Adopted from https://github.com/Dimillian/IceCubesApp @MainActor @Observable public class UserPreferences: ObservableObject { public static let shared = UserPreferences() class Storage { @AppStorage("user_id") public var userId: String = "" init() {} } private let storage = Storage() public var userId: String { didSet { self.storage.userId = self.userId } } ...
Theming
Theming - on one hand an expected feature for any modern App, on the other hand just somewhat of a bonus. But still, theming is a big cross cutting concern. Simply said: if your App progressed quite far and your try to implement a theming approach as an afterthought, you'll have touch most of your UI files again. But in contrast to the switch of a print-approach to a versatile logging, the search & replace-foo becomes tremendously more complex.
So lets introduce themes as an urgent concern.
Font Extensions
iOS has many accessibility options in its system preferences, and there are good accessibility solutions which can be implementd for visually impaired people. Still I believe, supporting fonts like OpenDyslexic or Atkinson Hyperlegible and font scaling (just like IceCube does) might just be a nice guesture modern Apps should consider.
By extending Font within our DesignSystem we can introduce custom and scaled font levels .The attirbute themeFont is a lookahead to the theme setting that we are looking at in the next chapter.
// Adopted from https://github.com/Dimillian/IceCubesApp @MainActor public extension Font { private static let title = 28.0 private static let headline = 17.0 private static let body = 17.0 private static let callout = 16.0 private static let subheadline = 15.0 private static let footnote = 13.0 private static let caption = 12.0 private static func themeFont(size: CGFloat, relativeTo textStyle: TextStyle) -> Font { if let chosenFont = Theme.shared.chosenFont { if chosenFont.fontName == ".AppleSystemUIFontRounded-Regular" { return .system(size: size, design: .rounded) } else { return .custom(chosenFont.fontName, size: size, relativeTo: textStyle) } } return .system(size: size, design: .default) } private static func scaledFontSize(baseSize: CGFloat) -> CGFloat { UIFontMetrics.default.scaledValue(for: baseSize * Theme.shared.fontSizeScale) } static var appTitle: Font { themeFont(size: scaledFontSize(baseSize: title), relativeTo: .title) } static var appdHeadline: Font { themeFont(size: scaledFontSize(baseSize: headline), relativeTo: .headline).weight(.semibold) } static var scaledBodyFocused: Font { themeFont(size: scaledFontSize(baseSize: body + 2), relativeTo: .body) } static var appBody: Font { themeFont(size: scaledFontSize(baseSize: body), relativeTo: .body) } static var appCallout: Font { themeFont(size: scaledFontSize(baseSize: callout), relativeTo: .callout) } static var appSubheadline: Font { themeFont(size: scaledFontSize(baseSize: subheadline), relativeTo: .subheadline) } static var appFootnote: Font { themeFont(size: scaledFontSize(baseSize: footnote), relativeTo: .footnote) } static var appCaption: Font { themeFont(size: scaledFontSize(baseSize: caption), relativeTo: .caption) } }
Theme Singleton
The sample above already introduced a singelton class called Theme , and alike the already seen UserPreferences this class uses the AppStorage to persist essential information.
// Adopted from https://github.com/Dimillian/IceCubesApp @MainActor @Observable public final class Theme { var logger: Logger = .init(subsystem: Bundle.main.bundleIdentifier!, category: String(describing: type(of: Theme.self))) public static let shared = Theme() final class ThemeStorage { enum ThemeKey: String { case colorScheme, tint, label, primaryBackground, secondaryBackground case selectedSet, selectedScheme case lineSpacing case followSystemColorSchme } @AppStorage("is_previously_set") public var isThemePreviouslySet: Bool = false @AppStorage(ThemeKey.selectedScheme.rawValue) public var selectedScheme: ColorScheme = .light @AppStorage(ThemeKey.selectedSet.rawValue) var storedSet: ColorSetName = .IceCubeLight @AppStorage(ThemeKey.followSystemColorSchme.rawValue) public var followSystemColorScheme: Bool = true @AppStorage(ThemeKey.tint.rawValue) public var tintColor: Color = .black @AppStorage(ThemeKey.primaryBackground.rawValue) public var primaryBackgroundColor: Color = .white @AppStorage(ThemeKey.secondaryBackground.rawValue) public var secondaryBackgroundColor: Color = .gray @AppStorage(ThemeKey.label.rawValue) public var labelColor: Color = .black @AppStorage("font_size_scale") public var fontSizeScale: Double = 1 @AppStorage(ThemeKey.lineSpacing.rawValue) public var lineSpacing: Double = 1.2 @AppStorage("chosen_font") public var chosenFontData: Data? init() {} } ...
Ricouard defines a theme by four colors tint, label , primaryBackground and secondaryBackground. He introduced the enumerations ColorSet and ColorSchema for management purpose.
public protocol ColorSet: Sendable { var name: ColorSetName { get } var scheme: ColorScheme { get } var tintColor: Color { get set } var primaryBackgroundColor: Color { get set } var secondaryBackgroundColor: Color { get set } var labelColor: Color { get set } } public enum ColorScheme: String, Sendable { case dark, light }
With these enumerations in place, a list of available theming-options (availableColorsSets) can be predefined like this
public struct IceCubeDark: ColorSet { public var name: ColorSetName = .iceCubeDark public var scheme: ColorScheme = .dark public var tintColor: Color = .init(red: 187 / 255, green: 59 / 255, blue: 226 / 255) public var primaryBackgroundColor: Color = .init(red: 16 / 255, green: 21 / 255, blue: 35 / 255) public var secondaryBackgroundColor: Color = .init(red: 30 / 255, green: 35 / 255, blue: 62 / 255) public var labelColor: Color = .white public init() {} } public struct IceCubeLight: ColorSet { // ... } public enum ColorSetName: String, Sendable { case iceCubeDark = "Ice Cube - Dark" case iceCubeLight = "Ice Cube - Light" // ... } public let availableColorsSets: [ColorSetCouple] = [.init(light: IceCubeLight(), dark: IceCubeDark()), // ... ]
This can be realized with some AppStorage-foo, too.
https://github.com/Dimillian/IceCubesApp/blob/1.10.32/Packages/DesignSystem/Sources/DesignSystem/Theme.swift
Applying the Theme
- 🤖 This chapter was AI-drafted based on manually created sourcecode. The draft was personally revised, manually changed in style, wording and compactness.
The actual application of the theme to views is handled by a dedicated ViewModifier called ThemeApplier, which is exposed via an extension on View:
public extension View { @MainActor func applyTheme(_ theme: Theme) -> some View { modifier(ThemeApplier(theme: theme)) } }
Any view that calls .applyTheme(Theme.shared) receives the full theme treatment in one step. The modifier does three things:
-
Tint: Sets
.tint(self.theme.tintColor)so all accent colors (buttons, toggles, navigation bars) use the theme's tint. -
Color scheme: Sets
.preferredColorScheme(self.actualColorScheme), which isnilwhen the app follows the system, or explicitly.light/.darkwhen the user has overridden the system preference. -
Auto-initialization: On
.onAppearit checks whether the theme has ever been set (isThemePreviouslySet). If not, it applies the default color set matching the current system scheme (heartLightorheartDark) and marks the theme as initialized. WhenfollowSystemColorSchemeis enabled, it also listens for system color scheme changes via.onChangeand swaps the active color set accordingly.
In practice a root view looks like this:
@Environment(Theme.self) private var theme var body: some View { NavigationStack { ContentView() } .applyTheme(theme) }
The Theme singleton itself exposes computed properties that produce reusable view components — for example theme.backgroundColor returns a LinearGradient background view that can be layered behind any content. The modifier also handles the initial color-set selection: on first launch it picks the matching light or dark set, and thereafter the user can switch themes through a ThemePreviewView that renders live previews of each ColorSet and calls theme.applySet(set:) on tap.
ViewModifiers
Corporate Identity
Documentation
Localization
- 🤖 This chapter was AI-drafted based on manually created sourcecode. The draft was personally revised, manually changed in style, wording and compactness.
For now, all translation keys follow prefix-notation and hierachy system as convention (e.g. label.id, label.show_exercises, label.okay).
The more modern approach is the use of Swift symbol keys, so strings are accessed via generated symbols:
Text(.welcomeTitle) Text(.questionProgress(questionNumber, questionCount))
The App did not yet need plural localization.
Previews
- https://medium.com/@wesleymatlock/how-to-use-swiftuis-preview-content-with-the-preview-macro-56037446603c
- https://www.avanderlee.com/swiftui/previews-different-states/
- https://stackoverflow.com/questions/79373525/how-to-mock-view-model-for-swiftui-previews
- https://www.hackingwithswift.com/quick-start/swiftdata/how-to-use-swiftdata-in-swiftui-previews
- https://peerdh.com/blogs/programming-insights/creating-a-mock-data-generator-for-swiftui-previews
- https://www.appcoda.com/swiftdata-preview/
- https://www.swiftbysundell.com/articles/getting-the-most-out-of-xcode-previews/
- https://www.avanderlee.com/xcode/preview-swiftui-uikit-appkit-views/
Testing
Clean Code
Conclusion
I did not finish my reading backlog (stored in Xavi Moll's beautiful and awesome later App), yet and there are many more things to discoer.
Sources
- Post banner by Microsoft Copilot:
Generate a futuristic construction site with skyscrapers in a warm orange light.
The individual sources are linked as reference, however I relied on these hounrable forerunners to cook my mashup.
- Antoine van der Lee
- Brian Advent
- Danijela Vrzan
- Jacob Bartlett
- Majid Jabrayilov
- The NSHipster Nate Cook & Matt
- Paul Hudson
- Peter Friese
- Simon B. Støvring
- Steward Lynch
- Thomas Ricouard
References
https://medium.com/geekculture/using-appstorage-with-swiftui-colors-and-some-nskeyedarchiver-magic-a38038383c5e
https://www.swiftyplace.com/blog/swiftui-font-and-texts
-
Antoine van der Lee - OSLog and Unified logging as recommended by Apple ↩
-
Apple Developer - Creating a standalone Swift package with Xcode ↩
-
Apple Developer - Organizing your code with local packages ↩
-
Brian Advent - iOS 13 SwiftUI Tutorial: Interactively Transition and Share Data between Views with SwiftUI ↩
-
Danijela Vrzan - Handle empty views in SwiftUI with ContentUnavailableView ↩
-
Danijela Vrzan - Handle TabView data in a type-safe way with Enums ↩
-
Peter Friese - Using View Modifiers to Display Empty State ↩
-
Paul Hudson - How To Use MVVWM to separate SwiftData from your Views ↩
-
https://www.hackingwithswift.com/quick-start/swiftui/whats-the-difference-between-observedobject-state-and-environmentobject ↩
-
https://stackoverflow.com/questions/71196212/swift-fetching-data-in-viewmodel-and-passing-it-to-view ↩↩
-
https://stackoverflow.com/questions/69725312/how-do-i-initialise-my-viewmodel-in-my-swiftui-app ↩
-
Majid Jabrayilov - Microapps architecture in Swift. SPM basics. ↩