Thomas
Thomas

Reputation: 35

generics in swift protocols

I am trying to migrate the Visitor pattern from my (old) java code to swift. So far I have a generic FIFO (working fine).

protocol FiFo {
    associatedtype U
    func enqueue(_ : U)
    func dequeue() -> U
}

I also want to tell the instance of the FIFO only to accept an instance of a visitor that uses the same type for the generic as the instance of the FIFO.

protocol Visitor {
    associatedtype T
    func processValue(_ value : T)
}
protocol FiFo {
    associatedtype U
    func enqueue(_ : U)
    func dequeue() -> U
    func visit(_ visitor : Visitor<U>)
}

Here I am facing:

Cannot specialize non-generic type 'Visitor'

Any hints? Thanks!

Upvotes: 3

Views: 112

Answers (2)

Martin R
Martin R

Reputation: 539685

You can make the visit method generic: Accept any visitor whose associated type T is the fifo's type U:

protocol FiFo {
    associatedtype U
    func enqueue(_ : U)
    func dequeue() -> U
    func visit<V: Visitor>(_ visitor : V) where V.T == U
}

Upvotes: 3

Rob
Rob

Reputation: 437392

You can add a constraint to an associated type:

protocol Visitor {
    associatedtype T
    func processValue(_ value : T)
}

protocol FiFo {
    associatedtype U
    associatedtype V: Visitor where V.T == U
    func enqueue(_ : U)
    func dequeue() -> U
    func visit(_ visitor: V)
}

Upvotes: 3

Related Questions