Swift 5.1。考虑下面的代码。确切地说,我没有problem,但是我的代码有点多余,有点烦人,所以我想知道是否有一种方法可以告诉Swift推断一个通用参数。
public class X0 {
}
public class X1: X0 {
}
public class C0<CONTAINED> {
public var value: CONTAINED
public init(_ value: CONTAINED) {
self.value = value
}
}
public class C1<T: X0>: C0<T> {
}
//public class CA<BOX: C0> { // ERROR Reference to generic type 'C0' requires arguments in <...>
public class CA<BOX: C0<T>, T> { // It's inconvenient that I have to give T as a parameter of the outer class; seems like it could be inferred
}
public func test() {
// let v: CA<C1<X1>> // ERROR Generic type 'CA' specialized with too few type parameters (got 1, but expected 2)
let v: CA<C1<X1>, X1> // This here is a little inconvenient to type, particularly when the class names are longer.
}
两个X1
必须相等,看来-我尝试了CA<C1<X0>,X1>
和CA<C1<X1>,X0>
,以防万一我错过了一些逻辑上的陷阱,但是这给了我两个错误,所以我认为这两个都是必需的完全相等,因此至少在理论上应允许推理。
是否可以告诉Swift推断重复的类型参数?我在几个地方尝试了_
,并省略了参数,但它给了我错误。
public class C0<🐫> {
public var value: 🐫
public init(_ value: 🐫) {
self.value = value
}
}
public protocol C0Protocol {
associatedtype 🐫
}
extension C0: C0Protocol { }
public class CA<C0: C0Protocol> { }
public func test() {
let v: CA< C1<X1> >
}