Use Combine for reactive programming in Swift
✓Works with OpenClaudeYou are a Swift reactive programming expert. The user wants to build reactive applications using Apple's Combine framework for handling asynchronous events and data streams.
What to check first
- Verify your project targets iOS 13+ or macOS 10.15+ (Combine's minimum deployment)
- Run
swift package describeif using Swift Package Manager to confirm Combine is available (built-in, no installation needed) - Check your ViewController or SwiftUI View imports include
import Combine
Steps
- Import Combine and create a Publisher by conforming to
ObservableObjectwith@Publishedproperties for reactive state - Define a Subscriber using a
.sink()operator to consume values and completion events - Chain operators like
.map(),.filter(), and.flatMap()to transform streams before subscription - Use
@StateObjector@ObservedObjectin SwiftUI to bind publishers directly to UI properties - Implement custom publishers by adopting the
Publisherprotocol withsubscribe(_:)method - Manage subscriptions with
AnyCancellableto prevent memory leaks and explicit cleanup - Combine multiple streams with operators like
.combineLatest(),.merge(), or.zip()for complex workflows - Handle errors with
.catch()or.replaceError()to create resilient reactive pipelines
Code
import Combine
import SwiftUI
// MARK: - ObservableObject with Published properties
class UserViewModel: ObservableObject {
@Published var username: String = ""
@Published var isLoading: Bool = false
@Published var errorMessage: String?
private var cancellables = Set<AnyCancellable>()
// Custom Publisher for API calls
func fetchUser(id: Int) -> AnyPublisher<User, URLError> {
URLSession.shared
.dataTaskPublisher(for: URL(string: "https://api.example.com/users/\(id)")!)
.map(\.data)
.decode(type: User.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
// Subscription with operators
func searchUsers(query: String) {
$username
.debounce(for: .milliseconds(500), scheduler: DispatchQueue.main)
.removeDuplicates()
.filter { !$0.isEmpty }
.flatMap { [weak self] searchTerm -> AnyPublisher<[User], Never> in
guard let self = self else { return Just([]).eraseToAnyPublisher() }
self.isLoading = true
return self.fetchUser(id: 1)
.map { [$0] }
.replaceError(with: [])
.eraseToAnyPublisher()
}
.handleEvents(receiveOutput: { _ in
self
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Swift / iOS Skills
Other Claude Code skills in the same category — free to download.
SwiftUI
Build SwiftUI views with state management and navigation
UIKit
Create UIKit view controllers with Auto Layout
Core Data
Set up Core Data with models, contexts, and fetch requests
Swift Networking
Build networking layer with URLSession and Codable
Swift Testing
Write XCTest unit and UI tests for iOS apps
Swift Async/Await Concurrency
Use Swift's structured concurrency for async code without callback hell
Swift CoreData Relationships
Model one-to-many and many-to-many relationships in CoreData
Want a Swift / iOS skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.