<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pallab Maiti on Medium]]></title>
        <description><![CDATA[Stories by Pallab Maiti on Medium]]></description>
        <link>https://medium.com/@pallabmaiti?source=rss-c8b857d1faa1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4P6znJ3RkkiSC5rHLyK0qw.jpeg</url>
            <title>Stories by Pallab Maiti on Medium</title>
            <link>https://medium.com/@pallabmaiti?source=rss-c8b857d1faa1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 17:31:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pallabmaiti/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How can I convert a completion handler to async/await?]]></title>
            <link>https://medium.com/@pallabmaiti/how-can-i-convert-a-completion-handler-to-async-await-42150868258c?source=rss-c8b857d1faa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/42150868258c</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Pallab Maiti]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 13:26:49 GMT</pubDate>
            <atom:updated>2025-06-09T13:26:49.793Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever written deeply nested closures that made your brain cry? 😅<br>If you’ve used completion handlers in Swift for a while, you know what I’m talking about.</p><p>Fortunately, Swift’s async/await syntax has arrived to save us from callback hell. This post is your practical guide to converting old-school completion handlers into modern, elegant, and readable async functions.</p><h3>The Old Way: Completion Handlers</h3><p>Let’s start with a classic:</p><pre>func fetchData(completion: @escaping (Result&lt;String, Error&gt;) -&gt; Void) {<br>    DispatchQueue.global().asyncAfter(deadline: .now() + 1) {<br>        completion(.success(&quot;Data loaded&quot;))<br>    }<br>}</pre><p>This function mimics an async API call and uses a completion block to return a Result. <em>Functional? </em><strong>Yes</strong><em>. Readable and modern? </em><strong>Not so much</strong><em>.</em></p><h3>The Modern Way: async/await</h3><p>We can wrap this function with async/await using Swift’s withCheckedThrowingContinuation.</p><p>Here’s how:</p><pre>func fetchData() async throws -&gt; String {<br>    return try await withCheckedThrowingContinuation { continuation in<br>        fetchData { result in<br>            switch result {<br>            case .success(let data):<br>                continuation.resume(returning: data)<br>            case .failure(let error):<br>                continuation.resume(throwing: error)<br>            }<br>        }<br>    }<br>}</pre><p>Now, instead of dealing with a completion block, you can write:</p><pre>Task {<br>    do {<br>        let result = try await fetchData()<br>        print(result)<br>    } catch {<br>        print(&quot;Error:&quot;, error)<br>    }<br>}</pre><p>Much easier to read and maintain.</p><h3>Completion Without Error? Use withCheckedContinuation</h3><p>If your completion handler <strong>doesn’t throw</strong>, use withCheckedContinuation instead:</p><pre>func loadProfile(completion: @escaping (UserProfile) -&gt; Void) {<br>    // simulate fetch profile<br>}<br><br>func loadProfile() async -&gt; UserProfile {<br>    return await withCheckedContinuation { continuation in<br>        loadProfile { profile in<br>            continuation.resume(returning: profile)<br>        }<br>    }<br>}</pre><h3>Under the Hood: Why Continuation?</h3><p>A continuation gives you a “handle” to resume the flow of execution once your async task completes. It bridges the old completion-handling world with Swift’s structured concurrency model.</p><ul><li>withCheckedContinuation → for non-throwing</li><li>withCheckedThrowingContinuation → for throwing code</li></ul><p>Swift even checks that you resume it exactly once, helping avoid bugs.</p><h3>Clean Up: Avoid Nested Closures</h3><p>By moving to async/await, your code becomes:</p><ul><li>Easier to read</li><li>Easier to test</li><li>Easier to reason about</li></ul><p>Say goodbye to pyramid-of-doom closures.</p><h3>When Should You Convert?</h3><p>Convert to async/await if:</p><ul><li>You’re using Swift 5.5+ and targeting iOS 13+ (with some caveats).</li><li>You want clearer, more maintainable code.</li><li>You’re building new APIs or modernizing existing ones.</li></ul><p>Leave the old completion-based methods behind. Your future self will thank you.</p><h3>TL;DR</h3><ul><li>Use withCheckedThrowingContinuation if you have completion: (Result&lt;T, Error&gt;) -&gt; Void</li><li>Use withCheckedContinuation if you have completion: (T) -&gt; Void</li><li>Also use withCheckedContinuation if you have completion: () -&gt; Void</li></ul><h3>Final Thoughts</h3><p>Swift’s concurrency system is powerful. With a little effort to wrap old functions, you’ll unlock a cleaner, more modern codebase. So go ahead wrap those handlers, and embrace the async life.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42150868258c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just Built My iOS Expense Tracker App with Swift + SwiftUI]]></title>
            <link>https://medium.com/@pallabmaiti/just-built-my-ios-expense-tracker-app-with-swift-swiftui-3e9c87f51d54?source=rss-c8b857d1faa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e9c87f51d54</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[insights-and-data]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Pallab Maiti]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 05:00:53 GMT</pubDate>
            <atom:updated>2025-04-15T08:31:46.169Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers, we always look for practical side projects to sharpen our skills, explore new frameworks, and even solve personal problems. Recently, I built a minimalist yet powerful <strong>Expense Tracker</strong> using <strong>SwiftUI</strong>, and in this post, I’ll break down the architecture, design principles, and technical challenges that went into it.</p><h3><strong>Overview</strong></h3><p>This iOS app helps users <strong>track income and expenses</strong>, <strong>view insights</strong>, and <strong>manage financial data</strong> — all wrapped in a dark, elegant UI with green accents.</p><p>Key features include:</p><ul><li>Dashboard for adding/editing transactions</li><li>Dynamic insights and statistics</li><li>Local database persistence</li><li>Modular MVVM architecture</li><li>Custom SwiftUI components</li></ul><h3>Project Architecture</h3><p>The app follows a clean <strong>MVVM architecture</strong>, ensuring separation of UI, logic, and data persistence:</p><pre>📂 ExpenseTracker<br>├── App Launch: ExpenseTrackerApp.swift<br>├── Views: SwiftUI screens for Dashboard, Transactions, Insights<br>├── ViewModels: Business logic &amp; state management<br>├── Models: Core data types like Transaction<br>├── Database: Custom local persistence layer<br>├── CustomViews: UI components<br>├── Utility: Enums, and extensions</pre><h4>App Entry Point</h4><p>The app launches with a custom splash screen before transitioning into the tab-based interface.</p><pre>@main<br>struct ExpenseTrackerApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            SplashScreenView()<br>        }<br>    }<br>}</pre><h4>Dashboard View</h4><p>The <strong>DashboardView</strong> shows recent income and expenses and allows users to add or edit them via modal sheets.</p><p><strong>ViewModel Setup</strong> (Business Logic)</p><pre>@Observable class ViewModel {  <br>    private(set) var expenses: [Expense] = []  <br>    func fetchExpenses() {  <br>        expenses = data.filterByCurrentMonth().sorted()  <br>    }  <br>}</pre><p>Its handles:</p><ul><li>Fetching and sorting transactions</li><li>Managing states</li><li>Coordinating database reads/writes</li></ul><p><strong>View</strong> (UI + Binding)</p><pre>struct DashboardView: View {  <br>    @State private var viewModel: ViewModel  <br>    var balance: Double { viewModel.expenses.total - viewModel.incomes.total }  <br>    <br>    var body: some View {  <br>        Text(&quot;\(balance, format: .currency(code: &quot;USD&quot;))&quot;)  <br>            .onAppear { viewModel.fetchExpenses() }  <br>    }  <br>}</pre><p><strong>Modular Sheets/Alerts</strong></p><pre>.sheet(isPresented: $viewModel.showAddExpense) {  <br>    AddExpenseView(onSave: viewModel.fetchExpenses)  <br>}</pre><p><strong>Why It Works</strong>:</p><ul><li><strong>Reactive</strong>: VM updates → UI auto-refreshes.</li><li><strong>Scalable</strong>: DI + private(set) enforce controlled state.</li><li><strong>Maintainable</strong>: Logic separated from UI.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*4SwW7j2T1RRzoXdocBqr5w.jpeg" /><figcaption>Dashboard view</figcaption></figure><p><a href="https://medium.com/@pallabmaiti/mastering-expense-tracking-with-swiftui-a-deep-dive-into-dashboard-view-b88f431b9187"><strong>A deep dive into Dashboard’s view</strong></a></p><h4>Transactions View</h4><p>The TransactionsView shows all income and expenses and allows users to filter them by date, amount, income source and expense category.</p><p><strong>Core Components:</strong></p><p><strong>Date Filter View</strong> — Clean date range selector with presets</p><pre>enum DateFilterOption: String, CaseIterable {<br>    case last30Days = &quot;Last 30 Days&quot;<br>    case last60Days = &quot;Last 60 Days&quot;<br>    case last90Days = &quot;Custom Range&quot;<br>}<br><br>private var selectedDateRange: (Date, Date)? {<br>    guard let option = selectedOption else { return nil }<br>    switch option {<br>    case .last30Days: return (Calendar.current.date(byAdding: .day, value: -30, to: Date())!, Date())<br>    // ... other cases<br>    }<br>}</pre><p><strong>Filter View</strong> — Horizontal filter selector UI</p><pre>struct FilterView: View {<br>    @Binding var selectedFilterOptions: Set&lt;FilterOption&gt;<br>    <br>    var body: some View {<br>        ScrollView(.horizontal) {<br>            HStack {<br>                ForEach(FilterOption.allCases) { option in<br>                    Button {<br>                        selectedFilterOptions.toggle(option)<br>                    } label: {<br>                        HStack {<br>                            Text(option.rawValue)<br>                            if selectedFilterOptions.contains(option) {<br>                                Image(systemName: &quot;xmark.circle.fill&quot;)<br>                            }<br>                        }<br>                    }<br>                    .tint(selectedFilterOptions.contains(option) ? .green : .gray)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>ViewModel Filter Logic</strong> — Combines multiple filters</p><pre>func filterTransactions() -&gt; [GroupedTransactions] {<br>    var filtered = allTransactions<br>    <br>    // Date filter<br>    if selectedFilterOptions.contains(.date) {<br>        filtered = filtered.filter { $0.date &gt;= startDate &amp;&amp; $0.date &lt;= endDate }<br>    }<br>    <br>    // Category filter<br>    if selectedFilterOptions.contains(.category) {<br>        filtered = filtered.filter { transaction in<br>            guard let expense = transaction as? Expense else { return true }<br>            return selectedCategories.contains(expense.category)<br>        }<br>    }<br>    <br>    // Group by month<br>    return Dictionary(grouping: filtered) { <br>        monthYearFormatter.string(from: $0.date) <br>    }.sorted { $0.key &gt; $1.key }<br>}</pre><p><strong>Key Features:</strong></p><ul><li><strong>Multiple filter types</strong> (date, category, amount, source)</li><li><strong>Combinable filters</strong> that work together</li><li><strong>Clean visual feedback</strong> for active filters</li><li><strong>Efficient grouping</strong> by month/year</li><li><strong>Type-safe enums</strong> for all filter options</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*09giTmCuJpNePDPgUtMZIA.jpeg" /><figcaption>Transactions view</figcaption></figure><p><a href="https://medium.com/@pallabmaiti/transaction-filtering-system-a-deep-dive-into-expensetrackers-transactions-view-4d9b36d781b3"><strong>A deep dive into Transactions’ view</strong></a></p><h4>Insights View</h4><p>The InsightsView shows an intuitive donut chart with custom legends to visualise monthly expenses/income using SwiftUI’s Charts framework with clean MVVM architecture.</p><p><strong>Key Components:</strong></p><p><strong>Chart Data Model</strong></p><pre>struct InsightsChartItem: Identifiable {<br>    let id: String<br>    let amount: Double<br>    let type: String  // &quot;Food&quot; or &quot;Salary&quot;<br>    let color: Color<br>    <br>    init(amount: Double, category: Category) {<br>        self.amount = amount<br>        self.type = category.rawValue<br>        self.color = colorForCategory(category)<br>    }<br>}</pre><p><strong>Donut Chart View</strong></p><pre>Chart {<br>    ForEach(list) { item in<br>        SectorMark(<br>            angle: .value(&quot;Amount&quot;, item.amount),<br>            innerRadius: .ratio(0.6), // Creates donut hole<br>            angularInset: 5<br>        )<br>        .foregroundStyle(item.color)<br>    }<br>}</pre><p><strong>Data Aggregation (ViewModel)</strong></p><pre>// Groups expenses by category and sums amounts<br>Category.allCases.forEach { category in<br>    let categoryExpenses = expenses.filter { $0.category == category }<br>    let total = categoryExpenses.reduce(0) { $0 + $1.amount }<br>    if total &gt; 0 {<br>        expenseList.append(InsightsChartItem(amount: total, category: category))<br>    }<br>}</pre><p><strong>Key Features</strong>:</p><ul><li>Dynamic donut charts with auto-generated legends</li><li>Month filtering of transactions</li><li>Empty state handling</li><li>Type-safe data modeling</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*idWdBF1SDyZ7a3OCrCw1rA.jpeg" /><figcaption>Insights view</figcaption></figure><p><a href="https://medium.com/@pallabmaiti/visualizing-financial-data-with-swiftui-charts-a-deep-dive-into-expensetrackers-insights-view-e79be9d5efa6"><strong>A deep dive into Insight’s View</strong></a></p><h4>Local Persistence Layer</h4><p>This app uses a <strong>protocol-oriented, thread-safe</strong> database layer with clear separation of concerns.</p><p><strong>Key Components:</strong></p><p>Database<strong> Protocol</strong> (Core Interface)</p><pre>protocol Database {<br>    var expenses: [DatabaseExpense] { get }<br>    func addExpense(_ expense: DatabaseExpense)<br>    // ... (similar for delete/update/clear)<br>}</pre><p><strong>Thread-Safe </strong>UserDefaults<strong> Implementation</strong></p><pre>class UserDefaultsDatabase: Database {<br>    private let queue = DispatchQueue(label: &quot;com.ExpenseTracker.Database&quot;)<br>    private var _expenses: [DatabaseExpense] = [] {<br>        didSet { saveToUserDefaults() } // Auto-persists changes<br>    }<br>    <br>    var expenses: [DatabaseExpense] {<br>        queue.sync { _expenses } // Thread-safe read<br>    }<br>    func addExpense(_ expense: DatabaseExpense) {<br>        queue.async(flags: .barrier) { <br>            self._expenses.append(expense) <br>        }<br>    }<br>}</pre><p><strong>Request Handling with </strong>DatabaseQuery</p><pre>enum DatabaseQuery {<br>    case getExpenses<br>    case addExpense(String, Double, String, String, String)<br>    case deleteExpense(String)<br>    // ...<br>}</pre><p><strong>Error Handling</strong></p><pre>enum ExpenseTrackerError: Error {<br>    case dataNotFound<br>    case invalidDateFormat<br>    // ...<br>}</pre><p><strong>Architecture Flow:</strong></p><pre>View/ViewModel → DatabaseManager → DatabaseHandler → DatabaseWorker → Database (UserDefaults/InMemory</pre><p><strong>Why It Works:</strong></p><ul><li><strong>Testable</strong>: Swap UserDefaultsDatabase with InMemoryDatabase for tests.</li><li><strong>Thread-Safe</strong>: GCD queues prevent race conditions.</li><li><strong>Extensible</strong>: Add new operations via DatabaseQuery.</li></ul><p><strong>Key Takeaway</strong>: Protocols + enums + thread safety = maintainable data layer.</p><p><a href="https://medium.com/@pallabmaiti/177781d87ddb"><strong>A deep dive into Database Architecture</strong></a></p><h3>UI/UX Design Choices</h3><p>Following Apple’s <strong>Human Interface Guidelines</strong>, the UI prioritizes:</p><ul><li>Accessibility: Good contrast, large tap targets</li><li>Dark Mode: Black background with red/green highlights</li><li>Smooth transitions: Using .sheet, .alert, and etc.</li></ul><h3>What Could Be Improved?</h3><p>Here’s what I’d consider next:</p><ul><li>Add unit tests for ViewModels</li><li>Implement biometric authentication</li><li>Sync data with iCloud or Firebase</li></ul><h3>Final Thoughts</h3><p>This Expense Tracker started as a utility project and turned into a deep dive into SwiftUI, MVVM, and local database management. Whether you’re just getting into iOS development or want to explore building production-quality apps with a local-first approach, this kind of project is a great sandbox.</p><p>If you’re interested in trying it out or contributing, the full code is available on <a href="https://github.com/pallabmaiti/expense-tracker">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e9c87f51d54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Robust Expense Tracker in Swift: A Deep Dive into Database Architecture]]></title>
            <link>https://medium.com/@pallabmaiti/building-a-robust-expense-tracker-in-swift-a-deep-dive-into-database-architecture-177781d87ddb?source=rss-c8b857d1faa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/177781d87ddb</guid>
            <category><![CDATA[thread-safety]]></category>
            <category><![CDATA[gcd]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Pallab Maiti]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 04:46:04 GMT</pubDate>
            <atom:updated>2025-04-15T04:46:04.313Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we’ll explore the architecture of a Swift-based Expense Tracker application, focusing on its database layer. This implementation showcases several important design patterns and best practices that make the code maintainable, testable, and thread-safe.</p><h3>The Core Database Protocol</h3><p>At the heart of our system is the Database protocol that defines all the operations our application needs:</p><pre>protocol Database {<br>    var expenses: [DatabaseExpense] { get }<br>    func addExpense(_ expense: DatabaseExpense)<br>    func deleteExpense(at index: Int)<br>    func updateExpense(at index: Int, with newExpense: DatabaseExpense)<br>    func clearExpenses()<br>    <br>    var incomes: [DatabaseIncome] { get }<br>    func addIncome(_ income: DatabaseIncome)<br>    func deleteIncome(at index: Int)<br>    func updateIncome(at index: Int, with newIncome: DatabaseIncome)<br>    func clearIncomes()<br>}</pre><p>This protocol-first approach gives us the flexibility to implement different storage solutions while maintaining a consistent interface.</p><h3>Two Database Implementations</h3><p>The system includes two concrete database implementations:</p><ol><li><strong>UserDefaultsDatabase</strong>: Persists data to UserDefaults using JSON encoding/decoding</li><li><strong>InMemoryDatabase</strong>: Stores data in memory, useful for testing and previews</li></ol><p>Both implementations use thread-safe operations with DispatchQueue to prevent race conditions:</p><pre>private let queue = DispatchQueue(label: &quot;com.ExpenseTracker.UserDefaultsDatabase&quot;)<br><br>var expenses: [DatabaseExpense] {<br>    queue.sync { [weak self] in<br>        guard let self else { return [] }<br>        return _expenses<br>    }<br>}<br>func addExpense(_ expense: DatabaseExpense) {<br>    queue.async(flags: .barrier) { [weak self] in<br>        guard let self else { return }<br>        _expenses.append(expense)<br>    }<br>}</pre><h3>The Layered Architecture</h3><p>The system follows a clean architecture with clear separation of concerns:</p><ol><li><strong>Database Layer</strong>: Raw storage operations (Database protocol implementations)</li><li><strong>Worker Layer</strong>: Business logic and error handling (DatabaseWorker)</li><li><strong>Handler Layer</strong>: Request processing (DatabaseHandler)</li><li><strong>Manager Layer</strong>: Application-facing API (DatabaseManager)</li></ol><p>This layered approach makes the code:</p><ul><li>Easier to test (each layer can be mocked)</li><li>More maintainable (changes are isolated)</li><li>More flexible (components can be swapped)</li></ul><h3>The Request/Response Pattern</h3><p>The system uses a neat DatabaseQuery enum to represent all possible operations:</p><pre>enum DatabaseQuery {<br>    case getExpenses<br>    case addExpense(String, Double, String, String, String)<br>    case updateExpense(String, String, Double, String, String, String)<br>    case deleteExpense(String)<br>    case deleteAllExpenses<br>    // ... income cases ...<br>}</pre><p>This pattern makes it easy to add new operations and keeps the handler code clean:</p><pre>func request(_ databaseQuery: DatabaseQuery, completion: @escaping (Result&lt;Data, Error&gt;) -&gt; Void) {<br>    switch databaseQuery {<br>    case .getExpenses:<br>        let expenses = databaseWorker.fetchExpenses()<br>        // ... serialize and return ...<br>    case let .addExpense(name, amount, date, category, note):<br>        let result = databaseWorker.saveExpense(name: name, amount: amount, date: date, category: category, note: note)<br>        // ... serialize and return ...<br>    // ... other cases ...<br>    }<br>}</pre><h3>Error Handling</h3><p>The system defines clear error cases in ExpenseTrackerError:</p><pre>enum ExpenseTrackerError: Error {<br>    case invalidDateFormat<br>    case invalidYear<br>    case invalidMonth<br>    case dataNotFound<br>}</pre><p>These are used consistently throughout the codebase, particularly in the worker layer where business logic resides.</p><h3>Practical Takeaways</h3><ol><li><strong>Protocol-oriented design</strong> makes your code more flexible and testable</li><li><strong>Thread safety</strong> is crucial for data operations — GCD queues are a simple solution</li><li><strong>Layered architecture</strong> helps manage complexity as your app grows</li><li><strong>Enum-based request patterns</strong> can make your code more declarative</li><li><strong>Clear error handling</strong> improves reliability and debugging</li></ol><p>This architecture could be extended with:</p><ul><li>A Core Data implementation of the Database protocol</li><li>Cloud synchronization capabilities</li><li>More sophisticated query capabilities</li></ul><p>The complete code shows how thoughtful design can create a maintainable, robust foundation for an expense-tracking app (or any data-driven application).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=177781d87ddb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Expense Tracking with SwiftUI: A Deep Dive into Dashboard View]]></title>
            <link>https://medium.com/@pallabmaiti/mastering-expense-tracking-with-swiftui-a-deep-dive-into-dashboard-view-b88f431b9187?source=rss-c8b857d1faa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b88f431b9187</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[derived-data]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Pallab Maiti]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 04:35:49 GMT</pubDate>
            <atom:updated>2025-04-15T04:35:49.980Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s post, we’ll explore a clean, maintainable approach to building a financial dashboard in SwiftUI. The DashboardView and its accompanying ViewModel demonstrate several key SwiftUI concepts that can elevate your app development skills.</p><h3>Key Architectural Decisions</h3><h4>1. Separation of Concerns</h4><p>The code follows a clear separation between:</p><ul><li><strong>Presentation</strong> (DashboardView): Handles UI rendering and user interactions</li><li><strong>Business Logic</strong> (ViewModel): Manages data processing and state</li></ul><pre>// In DashboardView<br>@State private var viewModel: ViewModel<br><br>// In ViewModel<br>private let databaseManager: DatabaseQueryType</pre><h4>2. Reactive Data Flow</h4><p>The ViewModel is marked with @Observable, enabling SwiftUI&#39;s automatic view updates when data changes:</p><pre>@Observable<br>class ViewModel {<br>    private(set) var expenseList: [Expense] = []<br>    private(set) var incomeList: [Income] = []<br>}</pre><h4>3. Computed Properties for Derived Data</h4><p>The view efficiently calculates totals without storing redundant state:</p><pre>var totalIncome: Double {<br>    viewModel.incomeList.reduce(0) { $0 + $1.amount }<br>}<br><br>var balance: Double {<br>    totalIncome - totalExpense<br>}</pre><h3>Implementation Highlights</h3><h4>Smart Data Fetching</h4><p>The ViewModel handles all data operations, including filtering to the current month and sorting:</p><pre>func fetchExpenses() {<br>    databaseManager.fetchExpenses { [weak self] result in<br>        // Filter and sort<br>        let filteredExpenses = expenses.filterByCurrentMonth()<br>        expenseList = filteredExpenses.sorted(by: .date, isDescending: true)<br>    }<br>}</pre><h4>Flexible Sorting System</h4><p>The implementation supports multiple sorting options with ascending/descending control:</p><pre>var sortingOption: SortingOption = .date<br>var isDescending: Bool = true<br><br>func sortExpenses() {<br>    expenseList = expenseList.sorted(by: sortingOption, isDescending: isDescending)<br>}</pre><h4>Comprehensive Alert Management</h4><p>The ViewModel centralizes all alert states:</p><pre>var showError: Bool = false<br>var errorMessage: String = &quot;&quot;<br>var showExpenseDeleteConfirmation: Bool = false<br>var expenseToDelete: Expense?</pre><h3>Best Practices Demonstrated</h3><h4><strong>1. Dependency Injection</strong>:</h4><pre>init(databaseManager: DatabaseQueryType) { <br>    self.databaseManager = databaseManager <br>}</pre><h4><strong>2. Type-Safe Currency Formatting</strong>:</h4><pre>Text(&quot;\(totalIncome, format: .currency(code: Locale.current.currency?.identifier ?? &quot;USD&quot;))&quot;)</pre><h4><strong>3. Modular Sheet Presentation</strong>:</h4><pre>.sheet(isPresented: $viewModel.showAddExpense) {<br>    AddExpenseView(databaseManager: databaseManager, onSave: viewModel.fetchExpenses)<br>}</pre><h3>Lessons for Your Projects</h3><ol><li><strong>ViewModel as a Single Source of Truth</strong>: Centralizing state management prevents bugs and makes behavior predictable.</li><li><strong>Reactive Composition</strong>: Computed properties keep your views in sync with minimal boilerplate.</li><li><strong>Testable Design</strong>: The clear separation between view and business logic makes unit testing straightforward.</li></ol><p>This implementation showcases how SwiftUI’s declarative syntax combined with thoughtful architecture can create powerful, maintainable applications. The patterns shown here apply to virtually any data-driven iOS app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b88f431b9187" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transaction Filtering System: A Deep Dive into ExpenseTracker’s Transactions View]]></title>
            <link>https://medium.com/@pallabmaiti/transaction-filtering-system-a-deep-dive-into-expensetrackers-transactions-view-4d9b36d781b3?source=rss-c8b857d1faa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d9b36d781b3</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Pallab Maiti]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 04:02:35 GMT</pubDate>
            <atom:updated>2025-04-15T04:02:35.002Z</atom:updated>
            <content:encoded><![CDATA[<p>In this analysis, we’ll examine the transaction filtering implementation in an Expense Tracker SwiftUI app, focusing on three key components: DateFilter</p><p>View, TransactionsView, and TransactionsViewModel.</p><h3>Architecture Overview</h3><p>The transaction filtering system follows a clean MVVM pattern:</p><ol><li><strong>View Layer</strong>: TransactionsView and DateFilterView handle UI presentation</li><li><strong>ViewModel Layer</strong>: TransactionsViewModel manages business logic and state</li><li><strong>Model Layer</strong>: Database interactions through DatabaseQueryType</li></ol><h3>Key Components</h3><h4>1. DateFilterView</h4><p>This component provides a clean interface for date range selection with several notable features:</p><pre>enum DateFilterOption: String, CaseIterable, Identifiable {<br>    case last30Days = &quot;Last 30 Days&quot;<br>    case last60Days = &quot;Last 60 Days&quot;<br>    case last90Days = &quot;Last 90 Days&quot;<br>    case customRange = &quot;Custom Range&quot;<br>    <br>    var id: String { rawValue }<br>}</pre><ul><li>Offers preset date ranges (30/60/90 days) and custom range option</li><li>Uses SwiftUI’s DatePicker with proper validation (end date can&#39;t be before start date)</li><li>Clean visual feedback with checkmarks for selected options</li></ul><h4>2. TransactionsView</h4><p>The main view coordinates between various filtering options and displays results:</p><pre>FilterView(selectedFilterOptions: $viewModel.selectedFilterOptions) { filterOption in<br>    switch filterOption {<br>    case .date:<br>        viewModel.showDateFilter.toggle()<br>    case .source:<br>        viewModel.showIncomeSourceFilter.toggle()<br>    case .category:<br>        viewModel.showExpenseCategoryFilter.toggle()<br>    case .amount:<br>        viewModel.showAmountFilter.toggle()<br>    }<br>}</pre><p>Key features:</p><ul><li>Horizontal filter selector with visual feedback</li><li>Integration with multiple filter types (date, category, source, amount)</li><li>Transaction list grouped by month with swipe actions</li><li>Search functionality</li></ul><h4>3. TransactionsViewModel</h4><p>The ViewModel handles all business logic and state management:</p><pre>private func filterTransactions() -&gt; [(key: String, value: [any Transaction])] {<br>    var filteredTransactions = allTransactions<br>    <br>    // Apply date filter<br>    if selectedFilterOptions.contains(.date) {<br>        filteredTransactions = filteredTransactions.filter { transaction in<br>            transaction.formattedDate &gt;= startDate &amp;&amp; transaction.formattedDate &lt;= endDate<br>        }<br>    }<br>    <br>    // Other filters...<br>    <br>    return grouped.sorted {<br>        guard let d1 = monthYearFormatter.date(from: $0.key),<br>              let d2 = monthYearFormatter.date(from: $1.key) else { return false }<br>        return d1 &gt; d2<br>    }<br>}</pre><p>Notable aspects:</p><ul><li>Comprehensive filtering logic combining multiple criteria</li><li>Proper error handling for database operations</li><li>State management for all UI interactions</li><li>Transaction grouping and sorting</li></ul><h3>Strengths of the Implementation</h3><ol><li><strong>Clean Architecture</strong>: Clear separation of concerns between view and logic</li><li><strong>Flexible Filtering</strong>: Supports multiple independent filter types</li><li><strong>User Experience</strong>: Visual feedback for active filters. Intuitive date selection. Responsive design</li><li><strong>Type Safety</strong>: Uses enums for filter options and categories</li><li><strong>Performance</strong>: Efficient grouping and sorting of transactions</li></ol><h3>Potential Improvements</h3><ol><li><strong>Filter Persistence</strong>: Save filter state between app launches</li><li><strong>Combined Filters</strong>: Add logical operators (AND/OR) between filters</li><li><strong>Undo Functionality</strong>: For deleted transactions</li><li><strong>Pagination</strong>: For large transaction sets</li><li><strong>Filter Indicators</strong>: More visible active filter indicators</li></ol><h3>Conclusion</h3><p>This implementation provides a robust foundation for transaction filtering in a financial app. The clean architecture and thoughtful UI design create a user-friendly experience while maintaining flexibility for future enhancements. The combination of preset date ranges with custom options offers both convenience and control, making it suitable for various user needs.</p><p>The code demonstrates several best practices in SwiftUI development, including:</p><ul><li>Proper state management</li><li>Clean view composition</li><li>Effective use of Swift language features</li><li>Thoughtful error handling</li><li>Responsive UI design</li></ul><p>Developers looking to implement similar functionality in their apps can use this as a reference for structuring complex filtering systems in SwiftUI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d9b36d781b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing Financial Data with SwiftUI Charts: A Deep Dive into ExpenseTracker’s Insights View]]></title>
            <link>https://medium.com/@pallabmaiti/visualizing-financial-data-with-swiftui-charts-a-deep-dive-into-expensetrackers-insights-view-e79be9d5efa6?source=rss-c8b857d1faa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e79be9d5efa6</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[data-aggregation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Pallab Maiti]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 03:57:31 GMT</pubDate>
            <atom:updated>2025-04-15T03:57:31.215Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s post, we’ll explore how to create beautiful, data-driven visualizations in SwiftUI by examining the Insights feature from an ExpenseTracker app. This implementation showcases how to transform raw financial data into intuitive donut charts with custom legends.</p><h3>The Power of Data Visualization</h3><p>Financial apps live and die by their ability to present complex data in understandable ways. Our InsightsView solves this by:</p><ol><li>Aggregating monthly income and expense data</li><li>Categorizing transactions by type</li><li>Presenting the information in clear visual formats</li></ol><h3>Key Components</h3><h4>1. The Chart Data Model</h4><p>The InsightsChartItem struct serves as our unified data model for visualization:</p><pre>struct InsightsChartItem: Identifiable {<br>    let id: String = UUID().uuidString<br>    let amount: Double<br>    let type: String<br>    let color: Color<br>    <br>    // Initializers for both expense categories and income sources<br>    init(amount: Double, category: Category) { ... }<br>    init(amount: Double, source: Source) { ... }<br>}</pre><p>This flexible structure allows us to handle both expenses and incomes while maintaining type safety through dedicated initializers.</p><h4>2. The Reusable Chart Component</h4><p>Our ChartView demonstrates SwiftUI&#39;s declarative power:</p><pre>struct ChartView: View {<br>    let list: [InsightsChartItem]<br><br>    var body: some View {<br>        Chart {<br>            ForEach(list) { item in<br>                SectorMark(<br>                    angle: .value(&quot;Amount&quot;, item.amount),<br>                    innerRadius: .ratio(0.6), // Donut effect<br>                    angularInset: 5<br>                )<br>                .cornerRadius(5)<br>                .foregroundStyle(item.color)<br>            }<br>        }<br>        // Plus legend implementation...<br>    }<br>}</pre><p>Key features:</p><ul><li>Uses SectorMark for pie/donut segments</li><li>Inner radius creates the donut effect</li><li>Custom corner radius for aesthetic appeal</li><li>Automatic legend generation</li></ul><h4>3. The ViewModel Magic</h4><p>The ViewModel handles all the business logic:</p><pre>class ViewModel {<br>    private(set) var expenseList: [InsightsChartItem] = []<br>    private(set) var incomeList: [InsightsChartItem] = []<br>    <br>    func fetchIncomes() {<br>        // 1. Fetch data<br>        // 2. Filter by current month<br>        // 3. Group by source and sum amounts<br>        // 4. Create chart items<br>    }<br>    <br>    func fetchExpenses() { <br>        // Similar process for expenses<br>    }<br>}</pre><p>The ViewModel follows clean architecture principles by:</p><ul><li>Keeping UI state</li><li>Handling data transformation</li><li>Managing business logic</li><li>Providing clean interfaces to the view</li></ul><h3>Implementation Highlights</h3><h4>Data Aggregation</h4><p>The ViewModel’s data processing is particularly elegant:</p><pre>// Group and sum by category<br>Category.allCases.forEach { category in<br>    let expenseByCategory = filteredExpenses.filter { $0.category == category }<br>    if !expenseByCategory.isEmpty {<br>        let total = expenseByCategory.reduce(0) { $0 + $1.amount }<br>        self.expenseList.append(.init(amount: total, category: category))<br>    }<br>}</pre><p>This approach:</p><ol><li>Iterates through all possible categories</li><li>Filters transactions for each</li><li>Calculates totals</li><li>Creates visualization-ready items</li></ol><h4>Empty State Handling</h4><p>The view gracefully handles empty states:</p><pre>if viewModel.expenseList.isEmpty {<br>    AddTransactionButton {<br>        viewModel.showAddExpense.toggle()<br>    }<br>} else {<br>    ChartView(list: viewModel.expenseList)<br>}</pre><h4>Date Filtering</h4><p>The month filtering demonstrates robust date handling:</p><pre>let filteredIncomes = incomes.filter {<br>    $0.formattedDate<br>        .formattedString(dateFormat: &quot;MMMM yyyy&quot;)<br>        .localizedCaseInsensitiveContains(self.currentMonth)<br>}</pre><h4>Lessons Learned</h4><ol><li><strong>SwiftUI Charts are powerful</strong> — With minimal code, we created professional visualizations</li><li><strong>ViewModels clean up complex views</strong> — Our InsightsView remains simple despite complex data</li><li><strong>Type safety matters</strong> — Dedicated initializers prevent category/source confusion</li><li><strong>Empty states are crucial</strong> — Always design for zero data scenarios</li></ol><h4>Extending the Feature</h4><p>Potential improvements:</p><ul><li>Add month/year picker for historical data</li><li>Implement swipe gestures between months</li><li>Add percentage labels to chart segments</li><li>Support dark/light mode theming</li></ul><h3>Conclusion</h3><p>The InsightsView demonstrates how SwiftUI’s declarative syntax combined with thoughtful architecture can create powerful data visualizations. By separating concerns between view, data, and business logic, we’ve built a maintainable, scalable feature that provides real value to users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e79be9d5efa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do you know you can test the Apple Push Notification service (APNs) in Simulator?]]></title>
            <link>https://medium.com/@pallabmaiti/do-you-know-you-can-test-the-apple-push-notification-service-apns-in-simulator-22abf475e8da?source=rss-c8b857d1faa1------2</link>
            <guid isPermaLink="false">https://medium.com/p/22abf475e8da</guid>
            <category><![CDATA[apple-push-notifications]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Pallab Maiti]]></dc:creator>
            <pubDate>Thu, 26 May 2022 16:06:10 GMT</pubDate>
            <atom:updated>2022-05-26T16:06:10.646Z</atom:updated>
            <content:encoded><![CDATA[<p>Remember those days when you want to test Push Notification in your career, and you have to rely on an iPhone itself. Yes, it’s a pain for those iOS developers who don’t have an iPhone device.</p><blockquote>Those days are over!!!</blockquote><p>Yes, now we can test <strong>Push Notification</strong> in <strong>iPhone Simulator</strong> itself, and we don’t need an <strong>iPhone</strong>. No need for <strong>Firebase Cloud Messaging</strong> also.</p><h3>Let’s get started</h3><blockquote><em>You will be needing Xcode 11.4 or later. Earlier versions of Xcode don’t support push notification using Simulator.</em></blockquote><h4>Enabling APNs</h4><p>You will need an Apple Developer subscription.</p><ol><li>You need to create an App Id with the <strong>Bundle Identifier</strong> in your developer a/c.</li><li>Add <strong>Push Notifications</strong> from <strong>Signing &amp; Capabilities</strong>.</li></ol><h4>Asking for User Notification Permission</h4><p>Add the above code in your <strong>AppDelegate</strong></p><blockquote>func requestAuthorization() {<br> UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in<br> guard granted else { return }<br> self?.getNotificationSettings()<br> }<br> }<br> <br> func getNotificationSettings() {<br> UNUserNotificationCenter.current().getNotificationSettings { settings in<br> guard settings.authorizationStatus == .authorized else { return }<br> DispatchQueue.main.async {<br> UIApplication.shared.registerForRemoteNotifications()<br> }<br> }<br> }</blockquote><p>Add above line at the end of <strong>application(_:didFinishLaunchingWithOptions:)</strong></p><blockquote>requestAuthorization()</blockquote><p>Build and run. You should receive a prompt that asks for permission to send you notifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ANNBamfOEsu9TIzQ6HSZdQ.png" /></figure><h4>Sending a Push Notification from Simulator</h4><p>Create a file called <strong>test.apn. </strong>Paste in the following <strong>JSON</strong> in that file.</p><blockquote>{<br> “aps”: {<br> “alert”: “My Push Notification”,<br> “sound”: “default”<br> }<br>}</blockquote><p>I preferred to keep that file in my project. You can save it anywhere.</p><p>Open <strong>Terminal </strong>and go to the directory where you saved <strong>test.apn</strong>. Then type in the following command: xcrun simctl push device_identifier bundle_identifier test.apn.</p><p>device_identifier: To get this identifier, in <strong>Xcode</strong>, go to <strong>Windows &gt;Devices and Simulators</strong>, then select the simulator you’re using from the list in <strong>the Simulators</strong> tab. Copy the identifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5KAdfNjo9kPrOIv5jNmMQ.png" /></figure><p>bundle_identifier App’s bundle identifier.</p><p>Example:</p><blockquote>xcrun simctl push C5DD81F6-AB11–4931-A73F-7A4EB076B482 com.test.apns.ios test.apn</blockquote><p>Voila, you can see the push notification in your Simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ahfO1akY9-BBcVECJp2eA.png" /></figure><h3>Final words</h3><p>I’ve just created a minimal example of how to test the Apple Push Notification service on Simulator. Of course, you shouldn’t stop there; you can play around by modifying the JSON.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22abf475e8da" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>