Cast a Swift generic class to a protocol with a typealias

Viewed 2769

Am I crazy or shouldn't this swift code compile?

protocol Protocol {
  typealias Thing
}

class Class<X>: Protocol {
  typealias Thing = X
}

func test<X:Protocol where X.Thing == Int> () -> X {
  return Class<Int>()  // error: cannot convert return expression of type 'Class<Int>' to return type 'X'
}

I can't seem to cast the object to its protocol even though the generic type and aliastype match.

EDIT:

I came up with the code above by extracting the logic out of my existing code in an effort to simplify the problem. I made some mistakes in doing so. Here is an updated (and hopefully less confusing) code sample:

protocol Protocol {
    typealias Thing
}
class Class<X>: Protocol {
    typealias Thing = X
}
func test<Y: Protocol where Y.Thing == Int> () -> Y {
    return Class<Y.Thing>()
}

I expected the compiler to allow test() to compile with the result type being Protocol<Int>.

3 Answers
Related