SwiftUI: Tips and Tricks

The following article lists some SwiftUI features and design patterns that I personally like to refer back to. The criteria was simply things that might not be immediately obvious to novice/intermediate Swift coder.

Nov 18, 2024

Custom Errors

Creating your own errors makes it much easier to handle your different error scenarios:

Creating

enum CustomError: Error {
    case invalidInput(String)
    case networkError(String)
    case unknown
}

Throwing

func performAction(input: String) throws {
    guard !input.isEmpty else {
        throw CustomError.invalidInput("Input cannot be empty.")
    }

Handling

do {
    try performAction(input: "network")
} catch CustomError.invalidInput(let message) {
    print("Invalid Input: \(message)")
} catch CustomError.networkError(let message) {
    print("Network Error: \(message)")
} catch {
    print("An unknown error occurred: \(error)")
}

Bindings

You can convert structures to bindings on-the-fly:

Binding(
    get: {
        viewModel.isSelected(activityType)
    },
    set: { newValue in
        viewModel.addSelection(activityType)
    }
)

If you just need a fixed value for a binding (typically useful for Previews):

.constant(.inProgress)

Tinted Toggles

Toggle(isOn: $showProgressBar) {
    Text("Show progress")
}
.toggleStyle(SwitchToggleStyle(tint: .primary))