快速嵌套通用参数推断

问题描述 投票:1回答:1

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推断重复的类型参数?我在几个地方尝试了_,并省略了参数,但它给了我错误。

swift generics type-inference
1个回答
0
投票
    您只能使用协议对其进行清理。
  1. 您不能将协议放入类型中,因此命名必须看起来像Objective-C。
  2. 使用骆驼箱!
  • 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> > }
  • © www.soinside.com 2019 - 2024. All rights reserved.