【发布时间】:2020-04-21 07:36:47
【问题描述】:
考虑以下代码:
public class Test<P: AnyObject> {
public func foo<T: P>(_ t: T.Type) -> T { // ERROR: Type 'T' constrained to non-protocol, non-class type 'P'
// stuff happens
}
}
注意第二行的错误,声称P 不是类类型。然而,在第 1 行,P 被声明为扩展 AnyObject,因此必须是类类型。因此,错误是不正确的。 ...正确的?这段代码和/或编译器是怎么回事?
编辑:这是一个给出五个类似通用函数的示例。它们每个都根据我想要的功能进行衡量,任何大写的 cmets 都会记录它们未能满足我的愿望的方式。为了使示例更加具体,我将AnyObject 替换为具体类C0。注意C2子类C1子类C0,而CX是不相关的。
public class C0 {
public required init() {
}
}
public class C1: C0 {
public required init() {
}
}
public class C2: C1 {
public required init() {
}
}
public class CX {
public required init() {
}
}
//public class D0<P: AnyObject> { // AnyObject replaced with C0 for a more concrete example
public class D0<P: C0> {
public func foo0<T: P>(_ t: T.Type) -> T { // DOESN'T COMPILE
return t.init()
}
public static func test_foo0() {
// let c2_0: C2 = D0<C1>().foo0(C2.self) // Function sig doesn't compile; can't test
// let cX_0: CX = D0<C1>().foo0(CX.self) // Function sig doesn't compile; can't test
}
// Shadows P in favor of its own local generic parameter P (T would accomplish the same result)
public func foo1<P>(_ t: P.Type) -> P { // TOO PERMISSIVE
return t.init() // Should compile ; does NOT compile
}
public static func test_foo1() {
let c2_1: C2 = D0<C1>().foo1(C2.self) // Should compile ; does compile
let cX_1: CX = D0<C1>().foo1(CX.self) // Should not compile ; DOES compile
}
public func foo2(_ t: P.Type) -> P { // TOO RESTRICTIVE
return t.init()
}
public static func test_foo2() {
let c2_2: C2 = D0<C1>().foo2(C2.self) // Should compile ; does NOT compile
let cX_2: CX = D0<C1>().foo2(CX.self) // Should not compile ; does not compile
}
// Hardcoded to match the constraint that is *on P*
public func foo3<T: C0>(_ t: T.Type) -> T { // TOO PERMISSIVE
return t.init()
}
public static func test_foo3() {
let c0_3: C0 = D0<C1>().foo3(C0.self) // Should not compile ; DOES compile
}
// Hardcoded to match the actual generic parameter of my example
public func foo4<T: C1>(_ t: T.Type) -> T { // HARDCODED TO MATCH MY SINGLE EXAMPLE
return t.init()
}
public static func test_foo4() {
let c2_4: C2 = D0<C1>().foo4(C2.self) // Should compile ; does compile
let c0_4: C0 = D0<C1>().foo4(C0.self) // Should not compile ; does not compile
let cX_4: CX = D0<C1>().foo4(CX.self) // Should not compile ; does not compile
}
}
第一个示例foo0 是我期望的,但它无法编译。在第五个示例foo4 中,我将泛型参数P 硬编码为C1,它应该在D0<C1> 中解析的方式,我在每个测试中使用的方式。这按预期工作,但不再是通用的。
我断言foo0 应该编译,并且(在D0<C1> 下)具有与foo4 相同的编译时行为。
【问题讨论】:
标签: swift generics compiler-errors generic-constraints