Skip to content

About

Polyformalism: Quilt in Swift (actors, @published, Combine)

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

🦅 quilt-swift

Quilt in the language Apple built for everything. Swift is the language that wanted to be modern, type-safe, and Apple-native all at once. It gave us actors for isolation, async/await for concurrency, property wrappers for reactive values, and the Combine framework for declarative reactive programming. When you express the Quilt cell model in Swift, you discover that Swift's @Published is exactly a Quilt cell. Combine is exactly a reactive engine. Actors are exactly cell isolation.

quilt-swift: Swift's @Published is exactly a Quilt cell

Why • Philosophy • What works • Workarounds • Deeper understanding

license version swift apple combine actors


✦ Why this exists

Apple has been quietly building the pieces of the cell model for fifteen years. Combine (2019) is a reactive framework with publishers, subscribers, and operators. @Published (2019) is a property wrapper that fires a publisher when the value changes. async/await (2021) is structured concurrency. Actors (2021) are isolated state. Property wrappers (2019) are reusable property logic.

Every single one of these is a piece of Quilt:

  • @Published is a ValueCell. A property wrapper that holds a value and publishes changes.
  • @State (in SwiftUI) is a ValueCell with view-binding. A property wrapper that holds state in a view.
  • Combine is a reactive engine. Publishers, subscribers, and operators.
  • Actors are cell isolation. An actor's properties are isolated from concurrent access.
  • async/await is deferred evaluation. An APICell is a Task<T>.

When you express the Quilt cell model in Swift, you find that the language already has the model. The polyformalism move: assemble the pieces Apple gave us, and you have Quilt.

This repo is the polyformalism port of Quilt to Swift. The same model, expressed in the language that quietly built the cell model into its standard library. The polyformalism insight: Swift's @Published is exactly a Quilt cell. Combine is exactly a reactive engine. Actors are exactly cell isolation.

✦ The philosophy

The Quilt model is language-independent. A cell is a typed unit of state. A formula is a function over dependencies. A listener is a callback. A sheet is a graph. The polyformalism question is: what does the model look like in the language that has a piece of the model for every primitive?

The Swift version emphasizes:

  • Property wrappers for cells. @ValueCell, @FormulaCell, @APICell are property wrappers. The polyformalism insight: property wrappers are cells done right.
  • Combine for the reactive engine. Combine's Publisher, Subscriber, and Operator are the reactive engine. The polyformalism insight: Combine is a reactive engine done right.
  • Actors for cell isolation. An actor Sheet is a sheet with isolated state. The polyformalism insight: actors are sheet isolation.
  • async/await for API cells. An APICell<T> is a Task<T>. The polyformalism insight: async/await is the deferred evaluation of cells.
  • Result builders for sheet construction. A sheet is built with a result builder that collects cells. The polyformalism insight: result builders are the cell DSL.

The polyformalism insight: Swift is the language where the cell model is a one-liner per piece. The polyformalism cost is the verbosity; the polyformalism benefit is the language was already designed for this.

✦ What works crazy well

1. @Published is exactly a ValueCell

Apple's @Published property wrapper holds a value and publishes changes via Combine. It is exactly a Quilt ValueCell.

import Combine

class BudgetSheet: ObservableObject {
    @Published var income: Double = 5000
    @Published var expenses: Double = 3000
    @Published var savings: Double = 0  // computed by the engine
}

// In the engine
let sheet = BudgetSheet()
sheet.$income
    .combineLatest(sheet.$expenses)
    .map { $0 - $1 }
    .assign(to: &sheet.$savings)

@Published var income is a ValueCell<Double> with the path "income". The polyformalism insight: Apple's @Published is a Quilt cell; we just didn't know it.

Polyformalism insight: the cell model in every language is a "thing that holds a value and publishes changes." Swift's @Published is exactly that. The polyformalism insight: the cell is a property wrapper; Swift is the language of property wrappers.

2. Combine is a reactive engine

Combine's Publisher, Subscriber, and Operator are the reactive engine. combineLatest, map, filter, merge — every reactive operator is there.

let savingsPublisher = sheet.$income
    .combineLatest(sheet.$expenses)
    .map { income, expenses in income - expenses }

let cancellable = savingsPublisher
    .sink { newSavings in
        print("Savings changed to: \(newSavings)")
    }

// In the formula cell
@FormulaCell(path: "savings", dependsOn: ["income", "expenses"])
func computeSavings(ctx: SheetContext) -> Double {
    return ctx.income - ctx.expenses
}

The polyformalism insight: Combine is a reactive engine; the reactive engine is a Publisher chain.

Polyformalism insight: the reactive engine in TypeScript is a graph walk. In Combine, it's a Publisher chain. The shapes are the same; Combine has the operators built in.

3. Actors for cell isolation

An actor Sheet is a sheet with isolated state. Concurrent access is safe by default.

actor BudgetSheet {
    private var cells: [String: any Cell] = [:]
    private var listeners: [String: [String]] = [:]
    
    func set(_ path: String, value: Any) async {
        cells[path] = ValueCell(path: path, value: value)
        await notifyListeners(of: path)
    }
    
    func get(_ path: String) -> Any? {
        return cells[path]?.value
    }
    
    private func notifyListeners(of path: String) async {
        for listener in listeners[path, default: []] {
            await evaluate(listener)
        }
    }
}

The polyformalism insight: actors are sheets; sheets are actors.

Polyformalism insight: the cell model in every language has a concurrency story. In Swift, the story is actors. The polyformalism insight: actors are the cell model's concurrency story.

4. Property wrappers for cell kinds

A property wrapper is a struct with a wrappedValue. The cell model can be expressed as a set of property wrappers.

@propertyWrapper
struct ValueCell<T> {
    let path: String
    private var _value: T
    private var publisher: PassthroughSubject<T, Never> = .init()
    
    var wrappedValue: T {
        get { _value }
        set {
            _value = newValue
            publisher.send(newValue)
        }
    }
    
    var projectedValue: AnyPublisher<T, Never> {
        publisher.eraseToAnyPublisher()
    }
}

@propertyWrapper
struct FormulaCell<T> {
    let path: String
    let deps: [String]
    let compute: (SheetContext) -> T
    // ... backed by a ValueCell that the engine updates
}

The polyformalism insight: property wrappers are the cell kind lattice; the cell kind lattice is a set of property wrappers.

Polyformalism insight: the cell kind in Pydantic is a BaseModel. In C#, it's a record. In Swift, it's a property wrapper. The polyformalism insight: cell kinds are reusable property logic; Swift is the language of property wrappers.

5. async/await for API cells

An APICell<T> is a Task<T>. The compiler generates the state machine.

@propertyWrapper
struct APICell<T> {
    let path: String
    let endpoint: URL
    private var task: Task<T, Error>?
    
    var wrappedValue: T {
        get async throws {
            if task == nil {
                task = Task {
                    let (data, _) = try await URLSession.shared.data(from: endpoint)
                    return try JSONDecoder().decode(T.self, from: data)
                }
            }
            return try await task!.value
        }
    }
}

// Usage
struct StockSheet {
    @APICell<Double>(path: "AAPL_price", endpoint: URL(string: "https://api.example.com/AAPL")!)
    var price: Double
}

// In an async context
let sheet = StockSheet()
let price = try await sheet.price  // Fetches on first access

The polyformalism insight: async/await is the deferred evaluation of cells.

Polyformalism insight: the cell model's deferred evaluation is async/await. Swift has it natively, with structured concurrency.

6. Result builders for sheet construction

A sheet is built with a result builder that collects cells.

@SheetBuilder
func budgetSheet() -> [any Cell] {
    ValueCell(path: "income", value: 5000.0)
    ValueCell(path: "expenses", value: 3000.0)
    FormulaCell(path: "savings", deps: ["income", "expenses"]) { ctx in
        ctx.get("income") - ctx.get("expenses")
    }
    ListenerCell(path: "on_savings", listen: "savings") { ctx in
        print("Savings: \(ctx.get("savings"))")
    }
}

let sheet = Sheet(cells: budgetSheet())

The polyformalism insight: result builders are the cell DSL; the cell DSL is a result builder.

Polyformalism insight: the cell kind in Pydantic is a class. In Swift, it's a result builder. The polyformalism insight: cell sheets are DSLs; Swift is the language of DSLs.

✦ What needs crazy workarounds

1. Verbosity for simple sheets

For a simple sheet with 5 cells, the Swift code is more verbose than the TypeScript or Python equivalent. The type system, the property wrappers, the publishers — they all add ceremony.

Workaround: Use the @SheetBuilder result builder. Or use Quilt.swift's convenience initializers. The polyformalism insight: the verbosity is the type system; the type system is the safety.

Insight gained: Swift's verbosity is a feature. The polyformalism insight: verbose languages force you to be explicit; explicit code is debuggable code.

2. Combine vs async/await

Combine is callback-based; async/await is structured. Mixing them is awkward.

Workaround: Use async/await for new code; use Combine for legacy UI code (SwiftUI). The polyformalism insight: Combine is the legacy reactive engine; async/await is the future.

Insight gained: the reactive engine has two eras in Swift. The polyformalism insight: Combine is the 2019 reactive engine; async/await is the 2021 reactive engine; the cell model uses both.

3. Property wrapper limitations

Property wrappers can't have stored properties that are also property wrappers. A FormulaCell that wraps a ValueCell is awkward.

Workaround: Use a Sheet class with computed properties. Or use Swift macros (Swift 5.9+) to generate the cell logic. The polyformalism insight: property wrappers have limits; Swift macros are the answer.

Insight gained: the cell model is a graph. Property wrappers are individual cells. The polyformalism insight: the cell graph is built with macros, not property wrappers.

4. Actor reentrancy

Actor methods are reentrant by default. A long-running formula can be interrupted.

Workaround: Use actor's reentrancy guard. Or split the formula into smaller pieces. The polyformalism insight: the cell model is a state machine; the state machine is the actor.

Insight gained: actors are state machines. The polyformalism insight: the cell model is a state machine; Swift's actors are the language-level expression of that.

✦ Deeper understanding

After implementing Quilt in Swift, the following insights emerge:

  1. Swift's @Published is exactly a Quilt cell. Apple built the cell model into the language. The polyformalism insight: Apple has been doing Quilt since 2019; they just didn't call it that.

  2. Combine is a reactive engine done right. Publishers, subscribers, and operators. The polyformalism insight: Combine is a reactive engine; the reactive engine is a Publisher chain.

  3. Actors are cell isolation done right. The actor's properties are isolated from concurrent access. The polyformalism insight: actors are sheets; sheets are actors.

  4. Property wrappers are the cell kind lattice. Each cell kind is a property wrapper. The polyformalism insight: property wrappers are the cell kind lattice.

  5. async/await is deferred evaluation done right. An APICell<T> is a Task<T>. The polyformalism insight: async/await is the deferred evaluation of cells.

  6. The polyformalism is about Apple's quiet revolution. Other languages reveal different facets. Swift reveals the Apple-native facet. The polyformalism insight: the cell model has been in Swift since 2019; we just assembled the pieces.

✦ Real-world scenarios

📱 iOS app state management — An iOS app's state is a Quilt sheet. @Published is the cell. Combine is the reactive engine. The view is a subscriber. The polyformalism insight: an iOS app is a Quilt sheet; SwiftUI is the view layer.

🍎 macOS document model — A macOS document is a Quilt sheet. Cells are document properties. Formulas are computed properties. Listeners are undo/redo triggers. The polyformalism insight: a document is a Quilt sheet; Document-based apps are Quilt apps.

🤖 LLM agent on Apple Silicon — An LLM agent runs on Apple Silicon. The agent's state is a Quilt sheet. The model is loaded into Metal buffers. The polyformalism insight: an LLM agent is a Quilt sheet; Metal is the inference engine.

⌚ watchOS health app — A watchOS health app has heart rate, steps, calories. The Quilt sheet has these as cells. Formulas compute derived metrics. Listeners notify the user. The polyformalism insight: a health app is a Quilt sheet; watchOS is the runtime.

✦ How it fits in the ecosystem

quilt-swift is the Apple-native layer of the Quilt polyformalism stack. The full set of 12 languages:

Language What it reveals What needs workarounds
TypeScript (canonical) Reactive evaluation is natural Hides the state machine structure
Tutor (1970) Multi-user cells are the default No closures, no async, no nested data
Pydantic-AI (Python) Type safety is the runtime contract Async overhead, slow interpreter
Mojo Cells are types, not values Young language, moving target
Julia The reactive engine is a type system No first-class sheets, compile latency
Chapel Cells are inherently parallel Verbose syntax, small ecosystem
COBOL Hierarchical cells map to divisions No closures
C The mathematical core No type safety, manual memory
C++ Type-erased cell kinds Templates explode, inscrutable errors
C# The enterprise-friendly version Heavy runtime, immutable records
Metal GPU-evaluated cells Host-device split, no dynamic dispatch
Swift (this) Apple's @Published is exactly a Quilt cell; Combine is a reactive engine; actors are cell isolation Verbosity, Combine vs async/await friction, property wrapper limits

The Swift version is for Apple platforms — the case where the cells must run on iOS, macOS, watchOS, or tvOS. The cell model is the same; the ecosystem is different.

✦ Why you should care

If you've ever wanted to write the cell model in a language that already had every piece. If you've ever wanted a cell to be a property wrapper, a reactive engine to be Combine, a sheet to be an actor.

This is for you.

Swift is the language that says: the cell model is not a new thing. Apple has been building the pieces for fifteen years. The polyformalism insight: the cell model is Swift; Swift is the cell model.

✦ License

Apache 2.0. See LICENSE.


@Published is a cell. Combine is a reactive engine. Actors are cell isolation. async/await is deferred evaluation. Property wrappers are the cell kind lattice. Swift is the cell model.

About

Polyformalism: Quilt in Swift (actors, @published, Combine)

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors