Ios

From j4flmao/agent-skills · View interactive version

Ios is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about iOS apps, SwiftUI screens and lists, UIKit, async image loading, Observation, navigation, Core Data, SwiftData or XCTest/Swift Testing on iOS. Produces iOS architecture, SwiftUI/UIKit code and tests. Not for Swift language features alone (use lang-swift) or macOS apps (u

How to use this skill

Skill file

iOS Native

Purpose

Build iOS native applications using Swift, SwiftUI/UIKit, MVVM+Coordinator architecture, Combine/async-await, Core Data, and XCTest.

Agent Protocol

Trigger

User request includes: ios, swift, swiftui, uikit, ios architecture, ios testing, ios native.

Input Context

Output Artifact

A markdown document containing:

Response Format

Produce the artifact directly. No preamble, no postamble, no explanations. No filler, no hedging, no transitions. Strip articles a/an/the where unambiguous. Compress output — why use many token when few do trick.

Max Response Length

4096 tokens

Workflow

Step 1: Set Up Project Structure

Organize code with feature-based folders: App, Features, Core (Network, Persistence, DI), and Common components.

Step 2: Implement MVVM with Coordinator

Create ViewModels with ObservableObject, Coordinators for navigation logic, and dependency injection container.

Step 3: Build UI with SwiftUI or UIKit

Use SwiftUI with @StateObject/@Published for reactive UI, or UIKit with programmatic view controllers and delegates.

Step 4: Set Up Persistence

Configure Core Data or SwiftData with NSPersistentContainer, context management, and save flows.

Step 5: Write Tests

Cover ViewModels with XCTest unit tests using mock services and UI flows with XCUITest.

Architecture Decision Trees

UI Framework Selection

Deployment target?
├── iOS 16+ → SwiftUI (native NavigationStack, SwiftData, Observable macros)
├── iOS 14-15 → SwiftUI with UIKit fallbacks for complex interactions
└── iOS 13- → UIKit (SwiftUI limited by deployment target requirement)
    
Team expertise?
├── New Swift team → SwiftUI (faster to build, less code)
├── Experienced UIKit team → UIKit for complex features, SwiftUI for simpler screens
└── Enterprise app with heavy custom UI → UIKit where SwiftUI lacks control; SwiftUI elsewhere

Architecture Pattern Selection

App complexity + team size?
├── Simple (<10 screens, CRUD) → MVVM
│   ViewModel @Observable, lightweight, quick to implement
├── Complex state management → TCA (The Composable Architecture)
│   Reducer pattern, testable, unidirectional, own your dependencies
├── Legacy codebase → VIPER
│   Strong separation, best for huge teams, more boilerplate
└── Multi-platform Swift → Clean Swift (VIP)
    Testable, clear boundaries, used with Swift on server too

Data Persistence Strategy

Data complexity?
├── Simple objects, light queries → SwiftData (iOS 17+)
│   Macro-based, Swift-native, auto-save, iCloud sync
├── Relational, existing Core Data → Core Data
│   Mature, complex queries, migration, iCloud, multi-threaded
├── Ephemeral, in-memory → UserDefaults + Codable
└── Full-text search, large datasets → GRDB (SQLite)
    Raw SQL control, migrations, combine publishers

Sync needed?
├── Yes → CloudKit + Core Data / SwiftData
├── No → Local persistence only
└── Real-time → Firebase Firestore

Concurrency Model

Task type?
├── One-shot network call → async/await (structured concurrency)
├── Stream of values → AsyncSequence (AsyncStream, AsyncAlgorithms)
├── Reactive chain → Combine (iOS 13+; still supported, but new code prefers async sequences)
└── Long-running observation → AsyncStream + @Observable (iOS 17+)

Project Structure

App/
├── Sources/
│   ├── App/
│   │   └── App.swift
│   ├── Features/
│   │   ├── Orders/
│   │   │   ├── OrderListView.swift
│   │   │   ├── OrderDetailView.swift
│   │   │   ├── OrderViewModel.swift
│   │   │   └── OrderCoordinator.swift
│   │   └── ...
│   ├── Core/
│   │   ├── Network/
│   │   ├── Persistence/
│   │   └── DI/
│   └── Common/
│       ├── Extensions/
│       └── Components/
└── Tests/
    ├── UnitTests/
    └── UITests/

MVVM + Coordinator

// OrderCoordinator.swift
final class OrderCoordinator: Coordinator {
    var navigationController: UINavigationController
    private let di: DIContainer

    init(navigationController: UINavigationController, di: DIContainer) {
        self.navigationController = navigationController
        self.di = di
    }

    func start() {
        let vm = OrderViewModel(service: di.orderService)
        vm.onSelectOrder = { [weak self] order in
            self?.showDetail(order)
        }
        let vc = OrderListViewController(viewModel: vm)
        navigationController.pushViewController(vc, animated: false)
    }

    private func showDetail(_ order: Order) {
        let vm = OrderDetailViewModel(order: order)
        let vc = OrderDetailViewController(viewModel: vm)
        navigationController.pushViewController(vc, animated: true)
    }
}

SwiftUI + async-await

// OrderViewModel.swift
@MainActor
@Observable
final class OrderViewModel {
    var orders: [Order] = []
    var isLoading = false
    var errorMessage: String?
    private let service: OrderService

    init(service: OrderService) {
        self.service = service
    }

    func loadOrders() async {
        isLoading = true
        errorMessage = nil
        do {
            orders = try await service.fetchOrders()
        } catch {
            errorMessage = error.localizedDescription
        }
        isLoading = false
    }
}

// OrderListView.swift
struct OrderListView: View {
    @State private var viewModel: OrderViewModel

    init(service: OrderService) {
        _viewModel = State(initialValue: OrderViewModel(service: service))
    }

    var body: some View {
        Group {
            if viewModel.isLoading {
                ProgressView()
            } else if let error = viewModel.errorMessage {
                ContentUnavailableView("Error", systemImage: "exclamationmark.triangle",
                    description: Text(error))
            } else {
                List(viewModel.orders) { order in
                    Text(order.customerName)
                }
            }
        }
        .task { await viewModel.loadOrders() }
    }
}

UIKit Programmatic

final class OrderListViewController: UIViewController {
    private let viewModel: OrderViewModel
    private let tableView = UITableView()
    private var dataSource: UITableViewDiffableDataSource<String, Order>!

    init(viewModel: OrderViewModel) {
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupTableView()
        bindViewModel()
    }

    private func setupTableView() {
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: view.topAnchor),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        dataSource = UITableViewDiffableDataSource(tableView: tableView) { tableView, indexPath, order in
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.text = order.customerName
            return cell
        }
    }

    // @Observable has no Combine publisher; re-register tracking after each change.
    // (iOS 26 UIKit can track Observable reads in viewWillLayoutSubviews/updateProperties automatically.)
    private func bindViewModel() {
        withObservationTracking {
            applySnapshot(viewModel.orders)
        } onChange: { [weak self] in
            Task { @MainActor in self?.bindViewModel() }
        }
    }

    private func applySnapshot(_ orders: [Order]) {
        var snapshot = NSDiffableDataSourceSnapshot<String, Order>()
        snapshot.appendSections(["main"])
        snapshot.appendItems(orders)
        dataSource.apply(snapshot, animatingDifferences: true)
    }
}

Core Data

// PersistenceController.swift
struct PersistenceController {
    static let shared = PersistenceController()
    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "AppModel")
        if inMemory {
            container.persistentStoreDescriptions.first?.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores { _, error in
            if let error = error { fatalError("\(error)") }
        }
        container.viewContext.automaticallyMergesChangesFromParent = true
    }

    var context: NSManagedObjectContext { container.viewContext }

    func save() throws {
        guard context.hasChanges else { return }
        try context.save()                       // let callers surface/log the error
    }

    // Background context for heavy operations
    func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) throws -> Void) {
        container.performBackgroundTask { context in
            do {
                try block(context)
                if context.hasChanges { try context.save() }
            } catch {
                Logger.persistence.error("Background save failed: \(error.localizedDescription, privacy: .public)")
            }
        }
    }
}

Testing (XCTest)

import XCTest
@testable import App

final class OrderViewModelTests: XCTestCase {
    var sut: OrderViewModel!
    var mockService: MockOrderService!

    override func setUp() {
        mockService = MockOrderService()
        sut = OrderViewModel(service: mockService)
    }

    override func tearDown() {
        sut = nil
        mockService = nil
    }

    func testLoadOrders() async {
        mockService.stubOrders = [Order(id: "1", customerName: "Test")]
        await sut.loadOrders()
        XCTAssertEqual(sut.orders.count, 1)
        XCTAssertFalse(sut.isLoading)
    }

    func testLoadOrdersFailure() async {
        mockService.shouldFail = true
        await sut.loadOrders()
        XCTAssertTrue(sut.orders.isEmpty)
        XCTAssertNotNil(sut.errorMessage)
    }
}

Production Considerations

SwiftUI Performance Patterns

UIKit Performance Patterns

Concurrency Safety

Anti-Patterns

Rules

References

Handoff

Hand off to mobile/universal/deployment/SKILL.md for deployment.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.