Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift array of protocols with associatedtype [duplicate]

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?

EDIT:

Sorry if i am late, but i was testing the solutions. As far as i understand the type-erase

AnyProt2<Prot1Type: Prot1>: Prot2

let me have a an array with

[AnyProt2<Prot1Class>] 

but i was asking for an array that could contain all kinds of AnyProt2 something like:

[AnyProt2] or [AnyProt2<Prot1>]

I tried the second but it gives me:

Using 'Prot1' as a concrete type conforming to protocol 'Prot1' is not supported.

In my context Prot1 is Interval and Prot2 is a Event, so i wanted to have and array with different kinds of Events that could have different kinds of Intervals. I also want to ask if it's possible to make Prot1 to extend Equatable and confirm the protocol in AnyProt2.

like image 788
4bottiglie Avatar asked Jul 04 '16 00:07

4bottiglie


1 Answers

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:

  • https://www.natashatherobot.com/swift-type-erasure/
  • Video: https://realm.io/news/tryswift-gwendolyn-weston-type-erasure/
  • http://krakendev.io/blog/generic-protocols-and-their-shortcomings
  • http://robnapier.net/erasure
  • https://realm.io/news/type-erased-wrappers-in-swift/
like image 193
Sash Zats Avatar answered Sep 28 '22 08:09

Sash Zats