SyntaxStudy
Sign Up
Swift Combine Framework Basics
Swift Beginner 1 min read

Combine Framework Basics

Combine is Apple's reactive programming framework, providing a declarative API for processing asynchronous events over time. Publishers emit values, operators transform them, and subscribers receive results. Published property wrapper creates a publisher for any property in an ObservableObject. SwiftUI subscribes automatically via @ObservedObject and @StateObject. Common operators include map, filter, flatMap, combineLatest, debounce, throttle, receive(on:), and sink (creates a subscriber that runs a closure).
Example
import Combine
import Foundation

// Simple publisher chain
let numbers = [1, 2, 3, 4, 5].publisher

let cancellable = numbers
    .filter { $0 % 2 == 0 }
    .map { $0 * $0 }
    .sink { print($0) }   // prints 4, 16

// ObservableObject with @Published
class UserViewModel: ObservableObject {
    @Published var searchText = ""
    @Published var results: [String] = []

    private var cancellables = Set<AnyCancellable>()

    init() {
        $searchText
            .debounce(for: 0.3, scheduler: RunLoop.main)
            .removeDuplicates()
            .filter { !$0.isEmpty }
            .map { text in ["Alice", "Bob", "Charlie"].filter { $0.lowercased().contains(text.lowercased()) } }
            .assign(to: &$results)
    }
}

// Timer publisher
let timer = Timer.publish(every: 1.0, on: .main, in: .common)
    .autoconnect()
    .scan(0) { count, _ in count + 1 }
    .prefix(5)
    .sink { print("Tick: \($0)") }