【问题标题】:Swift. Generic parameter 'T' could not be inferred迅速。无法推断通用参数“T”
【发布时间】:2021-07-26 10:51:46
【问题描述】:

我想创建一种映射对象的方法。所以我有这样的方法:

func testDecode<T: Decodable>(from: DocumentSnapshot) -> T? {
    do {
        return try from.data(as: T.self)
    } catch {
        return nil
    }
}

我是这样使用它的:

let test = testDecode(from: document.data) as? TestModel

但我有一个错误:Generic parameter 'T' could not be inferred 无法理解为什么我有这个错误,请给我建议

【问题讨论】:

  • 因隐藏错误而被否决。这个函数就是try?关键字。

标签: swift generics


【解决方案1】:

您不应尝试强制转换该值,而应将 test 注释为 TestModel? 以让编译器将泛型类型 T 推断为 TestModel

let test: TestModel? = testDecode(from: document.data)

【讨论】:

  • : TestModel?as TestModel? 相同。问号只需要移动即可。
  • 感谢您的回答,但有同样的错误Generic parameter 'T' could not be inferred
  • @vetaney915 请用DocumentSnapshot 的定义更新您的问题,特别是它的data(as:) 方法,因为这意味着问题将在那里
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 2019-10-19
  • 2023-03-11
  • 2021-11-13
相关资源
最近更新 更多