DEV Community

Programming Central
Programming Central

Posted on • Originally published at programmingcentral.hashnode.dev

Mastering AI UI: Building a Reusable, Animated Confidence Bar with Swift 6 and SwiftUI

In the world of AI-powered applications, delivering a result is only half the battle. The other half? Winning the user's trust. When an AI model makes a prediction, it isn't just "right" or "wrong"—it operates within a spectrum of certainty.

If your app tells a user their medical scan looks clear or their financial trend is bullish without explaining how sure it is, you’re operating a black box. To bridge this gap, we use the Confidence Bar. This UI component doesn't just show data; it communicates the "thought process" of your model through smooth, real-time animations.

In this guide, we’ll explore how to build a production-ready, reusable confidence bar using the latest Swift 6 features and SwiftUI.

Why Confidence Bars are Non-Negotiable for AI

AI models are probabilistic by nature. A confidence bar serves as a vital interpretability layer, offering several key benefits:

  1. Transparency: It pulls back the curtain on the model's internal state.
  2. User Agency: A low confidence score warns the user to double-check a result, preventing blind reliance on AI.
  3. Fluidity: In streaming scenarios (like live speech-to-text), an animated bar provides immediate feedback, making the app feel alive and responsive.
  4. Actionable Logic: Developers can use these scores to trigger specific UI states, such as asking for clarification if confidence drops below 50%.

The Architecture: AI Inference as a SwiftUI Update Cycle

To build this correctly, we need to understand the journey of a prediction. Think of AI inference as a high-stakes performance where the UI is the stage and the model is the backstage calculator.

  • The Actor (The Calculator): We use Swift Actors to handle Core ML inference. This ensures that heavy computations happen in an isolated environment, preventing the UI from freezing.
  • Async/Await (The Request): We use structured concurrency to "ask" for a prediction and wait for the result without blocking the main thread.
  • Sendable (The Result): The prediction data is wrapped in a Sendable type, a "certified slip" that guarantees the data can safely travel from the background actor to the main UI thread.
  • @observable (The Display Board): Using the new @Observable macro (iOS 17+), our UI automatically watches for changes in the confidence score and triggers a re-render the moment the data shifts.

Deep Dive: Key Swift 6 Features

Building this component leverages the cutting edge of Apple’s ecosystem:

1. The @Observable Macro

Gone are the days of bulky ObservableObject and @Published boilerplate. @Observable provides fine-grained tracking. It only updates the specific views that read a property, making your AI app significantly more performant.

2. Structured Concurrency

By offloading inference to an AIInferenceActor, we ensure thread safety. Swift 6 makes this even more robust by enforcing data isolation at compile time, virtually eliminating data races.

3. Declarative Animations

SwiftUI’s .animation() modifier allows us to turn abrupt data jumps into fluid transitions. When the AI model refines its guess, the bar grows or shrinks smoothly, providing a polished, "intelligent" feel.

Implementation: The Reusable Confidence Bar

Here is how you can implement a reusable ConfidenceBarView that responds to real-time AI state changes.

import SwiftUI
import Observation

// 1. Define the State using the @Observable macro
@available(iOS 17.0, *)
@Observable
class AIInferenceState {
    var confidenceScore: Double = 0.0
    var status: String = "Idle"

    func update(score: Double, label: String) {
        self.confidenceScore = score
        self.status = label
    }
}

// 2. Create the Reusable Component
struct ConfidenceBar: View {
    let value: Double
    let color: Color

    var body: some View {
        GeometryReader { geometry in
            ZStack(alignment: .leading) {
                RoundedRectangle(cornerRadius: 10)
                    .fill(Color.gray.opacity(0.2))
                    .frame(height: 12)

                RoundedRectangle(cornerRadius: 10)
                    .fill(color)
                    .frame(width: geometry.size.width * CGFloat(value), height: 12)
                    // The magic of SwiftUI animations
                    .animation(.spring(duration: 0.6), value: value)
            }
        }
        .frame(height: 12)
    }
}

// 3. Integrate into your View
struct AIInferenceView: View {
    @State private var state = AIInferenceState()

    var body: some View {
        VStack(alignment: .leading, spacing: 20) {
            Text("AI Confidence: \(Int(state.confidenceScore * 100))%")
                .font(.headline)

            ConfidenceBar(
                value: state.confidenceScore, 
                color: state.confidenceScore > 0.7 ? .green : .orange
            )

            Button("Simulate Inference") {
                Task {
                    // Simulate a background inference process
                    let newScore = Double.random(in: 0.1...1.0)
                    state.update(score: newScore, label: "Predicted")
                }
            }
        }
        .padding()
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

A confidence bar is more than just a UI widget; it’s a communication tool. By leveraging Swift 6 Actors, Structured Concurrency, and the Observation framework, you can build AI interfaces that are not only visually stunning but also technically robust and thread-safe.

When users can see how your AI thinks, they are far more likely to trust what it says.

Let's Discuss

  1. How do you handle "low confidence" scenarios in your apps? Do you hide the result entirely or show a warning to the user?
  2. With the shift to @Observable in Swift 6, have you found state management in complex AI workflows easier to debug?

Leave a comment below and let's talk about the future of AI-driven UI!

The concepts and code demonstrated here are drawn directly from the comprehensive roadmap laid out in the ebook
SwiftUI for AI Apps. Building reactive, intelligent interfaces that respond to model outputs, stream tokens, and visualize AI predictions in real time. You can find it here: Leanpub.com or Amazon.
Check also all the other programming ebooks on python, typescript, c#, swift: Leanpub.com or Amazon.

Top comments (0)