简体   繁体   中英

Swift protocols with mutually recursive associated type constraints in a function

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM