【问题标题】:Array of Decodable type is not decodableDecodable 类型的数组不可解码
【发布时间】:2019-09-26 22:02:03
【问题描述】:

如果我们有一个Foo: Decodable 类型,我们如何让Array<Foo> 可解码?

我是否必须创建另一个类型 Foos: Decodable

如果是这样,这将如何工作?


我在这里看到了问题

func exampleMethod<T:Decodable>(type: T) { }

// Argument type 'Array<Foo>.Type' does not conform to expected type 'Decodable'
exampleMethod(type: [Foo].self)

【问题讨论】:

  • 您的方法正在等待一个实例,您正在尝试传递类型。

标签: swift types decodable


【解决方案1】:

就用这个吧:

let res = JSONDecoder().decode([Foo].self, data)

你的情况:

exampleMethod(type: [Foo()])

关于exampleMethod 签名,你应该写一个数组。不是一种数组。

【讨论】:

  • 嗨,这确实有效,但是当我使用 类型的泛型参数创建方法时出现错误。我用一个例子更新了我的问题
  • 好的,谢谢你,这让我意识到我错误地使用泛型是个问题。你能把它写在你的问题中吗,我会把它标记为正确的。我正在传递类型,但它实际上是在期待一个值。
【解决方案2】:

如果Foo 符合Decodable,那么Array&lt;Foo&gt; 应该自动符合Decodable。这不是您在这种情况下看到的吗?

【讨论】:

  • 您好,我在使用泛型时遇到错误。我用一个例子更新了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-17
  • 2019-05-02
  • 2017-11-19
  • 2019-07-24
  • 2018-08-23
  • 1970-01-01
相关资源
最近更新 更多