Visitor Pattern 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
- ✓Visitor Pattern runs in O(n) time and O(n) space, in Swift as in every other language.
- ✓An enum with associated values plus an exhaustive switch is the idiomatic answer and needs no visitor at all, since the compiler requires every case to be handled.
- ✓Use the enum and switch for anything you own; a Swift reviewer will treat accept methods as a Java import.
- ✓The Swift trap: Swift has method overloading and resolves it statically, so a visitor built from overloaded visit methods binds on the static type of the argument, and a call with the value typed as the protocol always selects the protocol overload.
- ✓Switching on an enum is a tag branch and inlines well, so the enum form is the fast one. The protocol visitor dispatches through a witness table twice per node, once for accept and once for visit, and neither call inlines unless the type is known statically and the module is optimised as a whole.
What Visitor Pattern actually is
Visitor Pattern in Swift: what you actually reach for
Swift implementation
indirect enum Node {
case num(Double)
case add(Node, Node)
case mul(Node, Node)
}
// Exhaustive by construction: no accept(), no visitor protocol needed.
func evaluate(_ n: Node) -> Double {
switch n {
case .num(let v): return v
case .add(let l, let r): return evaluate(l) + evaluate(r)
case .mul(let l, let r): return evaluate(l) * evaluate(r)
}
}
// THE SWIFT-SPECIFIC TRAP: a method defined ONLY in a protocol extension is
// dispatched STATICALLY, so an override is not called through the protocol.
protocol Visitor {
func visitNum(_ v: Double) -> String // a REQUIREMENT: dynamic dispatch
}
extension Visitor {
func visitNum(_ v: Double) -> String { "default \(v)" }
func describe() -> String { "extension-only" } // NOT a requirement
}
struct Printer: Visitor {
func visitNum(_ v: Double) -> String { "num \(v)" }
func describe() -> String { "overridden" }
}
let p: any Visitor = Printer()
p.visitNum(1) // "num 1.0", requirement: the override runs
p.describe() // "extension-only": NOT a requirement: the default runsThink 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(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Visitor Pattern?
An enum with associated values plus an exhaustive switch is the idiomatic answer and needs no visitor at all, since the compiler requires every case to be handled. For a protocol-based hierarchy, a protocol with an accept method plus a visitor protocol reproduces the classical form. SwiftSyntax, the library Apple uses for its own tooling, ships a SyntaxVisitor class with a method per node kind and default implementations, which is the production example of the pattern in Swift.
What is the most common Swift mistake when implementing Visitor Pattern?
Swift has method overloading and resolves it statically, so a visitor built from overloaded visit methods binds on the static type of the argument, and a call with the value typed as the protocol always selects the protocol overload. That is the same trap as Java and it is why the accept bounce is needed there too. The Swift-specific version is worse in one respect: a default implementation supplied in a protocol EXTENSION for a method that is not a protocol requirement is dispatched statically, so a conformer that overrides it is not called through a protocol-typed reference, and the visitor silently runs the default.
How does Visitor Pattern actually perform in Swift?
Switching on an enum is a tag branch and inlines well, so the enum form is the fast one. The protocol visitor dispatches through a witness table twice per node, once for accept and once for visit, and neither call inlines unless the type is known statically and the module is optimised as a whole. Marking visitor classes final and using generic constraints instead of any lets the optimiser devirtualise both. Time complexity is O(n) 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 trialBefore paying for Replit, check its student and free-tier options 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.