10 Prompts for iOS Development with SwiftUI, UIKit, Core Data

10 Prompts for iOS Development with SwiftUI, UIKit, Core Data

As an iOS developer, you often face repetitive tasks: setting up a Core Data stack, debugging Auto Layout, or writing a network layer. Large language models can generate a solid starting point, but only if you prompt them precisely. This article provides ten battle-tested prompts for Swift-focused AI tools, each with a real-world example and code.

We'll reference Apple's official documentation as the authority: "Apple's SwiftUI documentation" and "Core Data Programming Guide".

Overview of Prompts

# Prompt Key skill
1 SwiftUI Lifecycle Understanding view modifiers
2 Auto Layout Debug Using po to inspect constraints
3 Core Data Stack Creating an NSPersistentContainer
4 NSFetchedResultsController Efficient table updates
5 Combine Networking Reactive API calls
6 Async/Await Modern concurrency
7 Custom View Modifier Reusable UI components
8 Unit Tests Testing ViewModels
9 Instruments Finding retain cycles
10 Codable vs Core Data Choosing storage

Now, let's go through each prompt.

1. SwiftUI View Lifecycle

Prompt: "Explain the difference between onAppear, task, and scenePhase in SwiftUI. Provide a code example that logs each event when the view appears and disappears."

Why it's useful: Many beginners use onAppear for network calls, but it doesn't guarantee cancellation. The task modifier automatically cancels async work when the view disappears. Here's a practical example:

struct ContentView: View {
    var body: some View {
        Text("Hello")
            .onAppear { print("Appeared") }
            .task {
                await fetchData()
            }
            .onDisappear { print("Disappeared") }
    }
}

According to Apple's documentation, task is ideal for starting asynchronous work tied to the view's lifetime.

2. UIKit Auto Layout Debugger

Prompt: "Debug the following Auto Layout error: 'Unable to simultaneously satisfy constraints'. Show the lldb command to print the view hierarchy and explain how to fix the constraint conflict."

This prompt is gold for UIKit developers. The typical error can be debugged with:

po yourView.perform(Selector(("_autolayoutTrace")))

Then identify the conflicting constraints. The prompt can be extended to generate a method that logs all constraints in a readable format.

3. Core Data Stack Setup

Prompt: "Create a modern Core Data stack using NSPersistentContainer (SwiftUI). Include lazy loading and error handling."

A well-structured prompt yields a reusable stack:

final class PersistenceController {
    static let shared = PersistenceController()
    let container: NSPersistentContainer

    init() {
        container = NSPersistentContainer(name: "Model")
        container.loadPersistentStores { _, error in
            if let error { fatalError("Error: \(error)") }
        }
    }
}

Reference: Apple's Core Data Programming Guide recommends using a single container for app-wide use.

4. NSFetchedResultsController in UIKit

Prompt: "Explain how to use NSFetchedResultsController with UITableView. Show how to handle delegate callbacks for row updates."

NSFetchedResultsController is still essential for UIKit. The prompt should include:

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
                didChange anObject: Any,
                at indexPath: IndexPath?,
                for type: NSFetchedResultsChangeType,
                newIndexPath: IndexPath?)

This avoids reloading the whole table.

5. Combine Networking Layer

Prompt: "Write a Combine publisher for a URLSession request that decodes JSON into a Codable struct. Include error handling."

Combine is a powerful framework. The prompt should produce code like:

struct User: Decodable { let id: Int; let name: String }

func fetchUser(id: Int) -> AnyPublisher<User, Error> {
    let url = URL(string: "https://api.example.com/user/\(id)")!
    return URLSession.shared.dataTaskPublisher(for: url)
        .map(\.data)
        .decode(type: User.self, decoder: JSONDecoder())
        .eraseToAnyPublisher()
}

For more context, see Apple's Combine documentation.

6. Modern Swift Concurrency in SwiftUI

Prompt: "Convert a URLSession call from completion handler to async/await and use it with .task in SwiftUI."

The result is straightforward:

func fetchUser(id: Int) async throws -> User {
    let (data, _) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode(User.self, from: data)
}

This reduces nesting and makes code easier to read.

7. Custom View Modifier

Prompt: "Create a custom ViewModifier that applies a card-style shadow and padding to any view, and then show how to use it in SwiftUI."

struct CardModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding(16)
            .background(Color.white)
            .cornerRadius(12)
            .shadow(color: .gray.opacity(0.4), radius: 4, x: 0, y: 2)
    }
}

extension View {
    func cardStyle() -> some View { modifier(CardModifier()) }
}

This is a practical, reusable pattern.

8. Unit Testing ViewModels

Prompt: "Write a unit test for a SwiftUI ViewModel that depends on a network service. Use protocol injection and XCTest."

Testing is crucial. The prompt should guide the AI to generate:

protocol UsersService { func fetch() async throws -> [User] }
class UsersViewModel: ObservableObject { ... }

Then, the test uses a mock service.

9. Instruments and Retain Cycles

Prompt: "Explain how to use the Leaks instrument in Xcode to detect retain cycles. Show a swift example of a closure that causes a cycle."

For example:

class MyClass {
    var closure: (() -> Void)?
    func setup() {
        closure = { [weak self] in
            self?.doWork()
        }
    }
}

The Leaks instrument is an essential tool for memory management.

10. Codable vs Core Data

Prompt: "Compare Codable structs and Core Data entities for a todo list app. When should you choose each?"

A detailed answer: Codable is great for straightforward persistence (JSON files), while Core Data offers undo, cloud sync, and efficient queries. Core Data adds complexity but is suitable for large datasets.

Conclusion

These ten prompts solve everyday iOS development problems. The key is to provide context, examples, and ask for code. With accurate prompts, you can save hours of debugging and boilerplate. Start using them in your next project, and adapt them to your specific architecture.

← All posts

Comments