【问题标题】:Generic parameter 'T' could not be inferred, Generic Error无法推断通用参数“T”,通用错误
【发布时间】:2020-08-10 08:34:03
【问题描述】:

我想创建一个函数来选择哪个实现好,像这样:

// As a BaseProtocol
protocol BaseProtocol {
    
}

// SeniorProtocol with associatedtype
protocol SeniorProtocol {
    associatedtype S
}

// First implementation of SeniorProtocol
struct SeniorImpl1:SeniorProtocol {
    typealias S = BaseProtocol
    init() {}
}

// Second implementation of SeniorProtocol
struct SeniorImpl2:SeniorProtocol {
    typealias S = BaseProtocol
    init() {}
}

// The function 
func whichImpl<T: SeniorProtocol>() -> T{
    if Int.random(in: 0 ... 5) < 3 {
        return SeniorImpl1() as! T
    }
    else {
        return SeniorImpl2() as! T
    }
}

最后,当我跑步时

var c = whichImpl()

我收到此错误:“无法推断通用参数 'T'”。 似乎编译器不知道 T 是什么。 我该如何解决?我只想做whichImpl()中写的代码

【问题讨论】:

  • 你想要达到什么目的?您对泛型的使用完全有缺陷,因为您返回的不是泛型类型,而是具体类型,因此会出现编译器错误。
  • 我只想返回一个符合协议“SeniorProtocol”条件的结构。因为'SeniorProtocol'有关联类型,所以不能是返回值。
  • 你必须做标准 Swift 库所做的事情:创建 AnySenior(类似于 AnyCollection) 类型擦除的包装器,然后返回它。
  • 我担心这是不可能的(我不确定这是否是个好主意)。 user28434 的解决方案可能是一个不错的解决方案。使用 some 关键字也不是一个选项:docs.swift.org/swift-book/LanguageGuide/OpaqueTypes.html#ID614。这个问题也可能有帮助:stackoverflow.com/questions/40034034/…。我认为如果您向我们提供更多背景信息将是最好的,这样我们就可以查看是否有更适合您的情况的解决方案。

标签: ios swift swiftui


【解决方案1】:

由于你的方法返回一个泛型类型 T 的值,那么你必须让 Swift 知道你希望你的 c 变量是哪个具体类型,以使 Swift 的类型检查系统工作。在您的情况下,只需给您的 c 一个像这样的具体类型即可使错误消失。

var c: Int = whichImpl()

【讨论】:

  • 恐怕这不是解决方案,因为Int 不符合SeniorProtocol(这是泛型类型T 的要求)。所以这不会编译。此外,这意味着您从SeniorImpl1SeniorImpl2 强制转换为Int(因为TInt),这将始终失败,因为它们没有任何关联。跨度>
  • 谢谢,但是符合[SeniorProtocol]的T在这种情况下只能是SeniorImpl1或SeniorImpl2。
  • 只是想澄清一下,我的回答只是一个选项,我们可以给 c 一个具体的类型。它不一定是Int。如果您不想这样做,您可以尝试一些类型擦除解决方案。但我不确定它是否适用于您的情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
  • 2019-06-10
  • 2015-09-22
相关资源
最近更新 更多