首页 > 解决方案 > Swift 嵌套泛型参数推断

问题描述

斯威夫特 5.1 。
考虑以下代码。确切地说,我没有问题,但是我的代码有点多余,而且有点烦人,所以我想知道是否有办法告诉 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 推断出重复的类型参数?_我在几个地方尝试过,并省略了参数,但它给了我错误。

标签: swiftgenericstype-inference

解决方案


  1. 您只能使用协议对其进行清理。
  2. 您不能将协议放在类型中,因此命名必须看起来像 Objective-C。
  3. 使用骆驼箱!
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> >
}

推荐阅读