Jason Silberman
Jason Silberman

Reputation: 2491

Is it possible to construct embedded generics in Swift?

Let's say I have a protocol and a struct like so:

protocol A {
    var someType: UnrelatedProtocol.Type { get }
}

struct B<T: UnrelatedProtocol> {
    var anotherThing: T?
}

And I want to use these together like this:

struct C<T: A> {
    typealias SomeThing = (B<T.someType>) -> Void
}

Is this possible in Swift? I have been playing around with this but cannot get it quite right. Maybe it's not possible but I feel like I should be able to do something like this.

Thanks!

Upvotes: 1

Views: 87

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59496

First of all we have

protocol UnrelatedProtocol { }

Now we need to define an associated type inside the protocol A

protocol A {
    associatedtype SomeType: UnrelatedProtocol
    var someType: SomeType { get }
}

And finally

struct B<T: UnrelatedProtocol> {
    var anotherThing: T?
}

struct C<T: A> {
    typealias Logic = (B<T.SomeType>) -> ()
}

Upvotes: 1

Related Questions