Swift protocols with mutually recursive associated type constraints in a function

Viewed 182

Is it possible to constrain two generic parameters associated types in a function to each other?

I'm trying to do something like this:

protocol One {
    associatedtype first: Two
}

protocol Two {
    associatedtype second: One
}

func f<O: One, T: Two>(o: O) -> T where O.first == T, T.second == O {
    fatalError()
}

It fails with the errors:

'first' is not a member type of 'O'

'second' is not a member type of 'T'
1 Answers

I was able to get this compile by removing one of the constraints on the function:

func f<O: One, T>(o: O) -> T where O.first == T, T.second == O {
    fatalError()
}

You don't need to say that T conforms to Two because that's already implied by O.first == T (because O.first must conform to Two). Once I took that out, this compiled.

Related