Event Sourcing Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Event Sourcing runs in O(1) append time and O(n) space, in Swift as in every other language.
- ✓An enum with associated values is the event set, and switch over it is exhaustive without a default.
- ✓reduce(into:) rather than reduce, because state is a value type and the returning form copies it once per event.
- ✓The Swift trap: Swift synthesises Codable for enums with associated values by keying off the case name and the parameter labels, so renaming .deposited to .credited, or renaming its cents label, silently changes the on-disk shape and every older event stops decoding.
- ✓COW is the whole performance story. reduce(into:) keeps the state's buffer uniquely referenced so appends stay in place; any stray retained reference flips every subsequent mutation into a full copy.
What Event Sourcing actually is
Event Sourcing in Swift: what you actually reach for
Swift implementation
import Foundation
enum Event: Decodable, Sendable {
case deposited(cents: Int)
case withdrawn(cents: Int)
// Hand-written because this stores a FLAT {type, cents} envelope, not the nested
// single-key object the synthesised coder emits. A pure RENAME would not need this:
// a top-level CodingKeys case, plus a nested DepositedCodingKeys, retargets names.
enum CodingKeys: String, CodingKey { case type, cents }
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let cents = try c.decode(Int.self, forKey: .cents)
switch try c.decode(String.self, forKey: .type) {
case "deposited": self = .deposited(cents: cents)
case "withdrawn": self = .withdrawn(cents: cents)
case let other:
throw DecodingError.dataCorruptedError(
forKey: .type, in: c, debugDescription: "unknown event \(other)")
}
}
// encode(to:) is the mirror image and must be written by hand too
}
struct Account: Sendable { var cents = 0; var version = 0 }
func replay(_ events: [Event], from snapshot: Account = Account()) -> Account {
// reduce(into:) keeps the buffer uniquely referenced, so COW never deep-copies per event
events.reduce(into: snapshot) { acc, event in
switch event {
case .deposited(let c): acc.cents += c
case .withdrawn(let c): acc.cents -= c
}
acc.version += 1
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(1) append
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Event Sourcing?
An enum with associated values is the event set, and switch over it is exhaustive without a default. Foundation gives JSONEncoder and JSONDecoder plus Codable; set dateEncodingStrategy and dateDecodingStrategy to .iso8601 explicitly, because the default .deferredToDate writes a Double of seconds since 2001-01-01. reduce(into:) from the standard library is the fold, UUID makes event ids, and an actor is the natural per-stream serialisation point so the version check and the append cannot interleave. Events carry Sendable so they can cross that actor boundary.
What is the most common Swift mistake when implementing Event Sourcing?
Swift synthesises Codable for enums with associated values by keying off the case name and the parameter labels, so renaming .deposited to .credited, or renaming its cents label, silently changes the on-disk shape and every older event stops decoding. CodingKeys alone can absorb a rename: a top-level CodingKeys case pins each case's wire name, and a nested DepositedCodingKeys pins that case's labels. Only a shape change needs init(from:) and encode(to:) by hand. The other one is copy-on-write: hold any second reference to the state's storage while folding, a snapshot array or a captured closure, and the refcount rises above one so every mutation inside apply deep-copies the whole collection, turning an O(n) replay into O(n squared) with no code change visible at the call site.
How does Event Sourcing actually perform in Swift?
COW is the whole performance story. reduce(into:) keeps the state's buffer uniquely referenced so appends stay in place; any stray retained reference flips every subsequent mutation into a full copy. ARC retain and release traffic is real in a tight loop, which is why value-type enum payloads beat class-based events. Passing events as any Event through an existential adds dynamic dispatch and boxes any payload larger than three words, whereas a concrete enum is statically dispatched and stays inline. Foundation's JSONDecoder is comparatively slow, so snapshot aggressively. Time complexity is O(1) append and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.