4bottiglie 4bottiglie - 5 months ago 28
Swift Question

Swift array of protocols with associatedtype

I have the first protocol

protocol Prot1
{

}


And the second:

protocol Prot2
{
associatedtype P: Prot1

func doSomething(param: P)
}


How can i make an array with the type Prot2?

I tried:

var myArray = [Prot2]()


But it gives me this error: Protocol Prot2 can only be used as a generic constraint because it has Self or associated type requirements

Is there any other way to make a template protocol?

Answer

Depending on your use case, you might get away with using generics, like so:

protocol Prot1 {
}

protocol Prot2 {
    associatedtype P: Prot1
    func doSomething(param: P)
}

class MyClass<T: Prot2> {
    var arr: [T] = []
}

But this solution pretty much defers the specifying of the concrete type implementing Prot2 and making consumer of MyClass to deal with that.

Sounds like your case would require to use something called "type erasure". Unfortunately, I won't be able to explain it here, but here are some really great articles and even talks that helped me to understand the concept: