In Swift, how to cast to protocol with associated type?

前端 未结 3 2016
暗喜
暗喜 2020-12-14 02:22

In the following code, I want to test if x is a SpecialController. If it is, I want to get the currentValue as a SpecialValue

3条回答
  •  自闭症患者
    2020-12-14 02:48

    [Edited to fix: : SpecialValue, not = SpecialValue]

    This is not possible. SpecialValueController is an "incomplete type" conceptually so the compiler cannot know. SpecialValueType, although it is constrained by SpecialValue, it is not known until it is determined by any adopting class. So it is a really placeholder with inadequate information. as?-ness cannot be checked.

    You could have a base class that adopts SpecialController with a concrete type for SpecialValueController, and have multiple child classes that inherit from the adopting class, if you're still seeking a degree of polymorphism.

提交回复
热议问题