键入检查具有泛型类型的类

时间:2022-04-05 16:27:52

I have a class like SomeController<A where A: ProtA>

我有一个类SomeController ,其中a:prota>

I have some subclasses like SubController: SomeController<SubA>

我有一些子类,如SubController:SomeController

Here's a working example of how I'm trying to type check:

这是我如何尝试键入检查的一个工作示例:

protocol SomeProtocol {

}

class SuperClass<A where A: SomeProtocol> {

}

class SubProtocol: SomeProtocol {

}

class SubClass: SuperClass<SubProtocol> {

}

func classTest<A where A: SomeProtocol>(classToTest: SuperClass<A>) {
    switch classToTest {
    case is SubClass: // Has warning 'Cast from SuperClass<A> to SubClass always fails'
        print("I'm a SubClass")

    default:
        print("Wasn't found")
    }
}

classTest(SubClass()) // Prints "I'm a SubClass"

Functionally, the code does exactly what I want, however, I'm left with a ton of warnings saying Cast from SuperClass<A> to SubClass always fails

在功能上,代码完全符合我的要求,但是,我留下了大量的警告,说从SuperClass 到SubClass的Cast始终失败

Clearly the types are related, and clearly the code runs fine and doesn't 'always fail', so this warning seems to be wrong. Is this a current limitation or edge case of the type system, or is there a way to make the warning go away?

很明显,这些类型是相关的,显然代码运行良好并且不会“总是失败”,所以这个警告似乎是错误的。这是类型系统的当前限制或边缘情况,还是有办法使警告消失?

1 个解决方案

#1


0  

Defining SuperClass as it's own generic suppresses the warning. I also don't think you need a where clause to specify that A conforms to SomeProtocol.

定义SuperClass,因为它自己的通用会抑制警告。我也认为你不需要where子句来指定A符合SomeProtocol。

func classTest<A:SomeProtocol, B:SuperClass<A>>(classToTest: B, useA:A) {

    switch classToTest {
    case is SubClass: // Has warning 'Cast from SuperClass<A> to SubClass always fails'
        print("I'm a SubClass")

    default:
        print("Wasn't found")
    }
}

#1


0  

Defining SuperClass as it's own generic suppresses the warning. I also don't think you need a where clause to specify that A conforms to SomeProtocol.

定义SuperClass,因为它自己的通用会抑制警告。我也认为你不需要where子句来指定A符合SomeProtocol。

func classTest<A:SomeProtocol, B:SuperClass<A>>(classToTest: B, useA:A) {

    switch classToTest {
    case is SubClass: // Has warning 'Cast from SuperClass<A> to SubClass always fails'
        print("I'm a SubClass")

    default:
        print("Wasn't found")
    }
}