The visitor pattern
When building complex algorithms, it is practical to separate the algorithm from the objects it operates on. The visitor pattern helps achieve such separation. One of the direct effects of using the visitor pattern is the ability to implement multiple distinct operations, without changing the underlying object structure.
The visitor pattern can be described through the series of protocols that each object has to implement:
- Define a
Visitable
protocol. Elements that can be visited implement this protocol. - Define a
Visitor
protocol.Visitor
objects implement this protocol, which helps them traverseVisitable
objects. - Extend existing objects to be
Visitable
. - Implement one or many
Visitor
objects and their logic.
Visitable and visitor protocols
Thanks to Swift and its expressive generics, it is possible to abstract the visitor pattern through a series of protocols:
protocol Visitor { func visit<T>(element: T) whereT:Visitable }
A Visitor
is an object that can traverse Visitable...