【问题标题】:Unable to cast Array<Codable> to Codable无法将 Array<Codable> 转换为 Codable
【发布时间】:2018-10-21 20:06:24
【问题描述】:

鉴于Array 符合Codable,我假设Codable 的数组,即[Codable] 肯定可以转换为Codable。 我用Decodable 部分做了一个简单的例子。只是为了验证:

// Attempt to conform Array to Decodable
extension Array : Decodable { }

这会导致警告:Conformance of 'Array&lt;Element&gt;' to protocol 'Decodable' conflicts with that stated in the type's module 'Swift' and will be ignored; there cannot be more than one conformance, even with different conditional bounds

这是有道理的,因为 Array 已经符合 Decodable

// Totally decodable array
var array: [Decodable] = ["Decodable", "strings"]

// Attempt to cast the decodable array
var decodable: Decodable = array

这会导致编译器错误:Value of type [Decodable] does not conform to specified type 'Decodable'

还有一个 FixIt:Insert 'as! Decodable'

应用 FixIt 会导致运行时错误:Could not cast value of type 'Swift.Array&lt;Swift.Decodable&gt;' (0x11f84dd08) to 'Swift.Decodable' (0x11f84db18).

我在 macOS 10.14 上使用 Xcode 10。

那么我在这里做错了什么?

编辑:我刚刚尝试使用 Xcode 9.2 并且相同的示例工作正常。所以问题就变成了为什么这不再适用于 Xcode 10,而我应该做什么呢?我在任何地方都找不到有关此更改的任何参考。

【问题讨论】:

  • 请先说出你想做什么;你要解码什么 JSON?
  • @meaning-matters 在这种情况下是字符串“Decodable”和“strings”。重点不在于。我已经知道解码后的数据是什么。您可以用Encodable 替换示例中每个出现的Decodable 并得到相同的错误。关键是代码不会编译。 @vadian [Decodable] 表示Array&lt;Decodable&gt; 表示Array,其中ElementDecodable。扩展只是为了证明 Array 确实已经符合 Decodable,正如您所指出的,它的要求是其 Element 泛型符合 Decodable

标签: arrays swift codable swift4.2


【解决方案1】:

根据 Swift 4.2 中生效的条件一致性法则:

(在 Swift 4.2 之前发生的事情是条件一致性不存在,我们只是获得了一种通用通行证;您可以将 any 数组视为可解码的,并且您不会遇到如果你错了,直到运行时才会出现问题。现在,通过条件一致性,编译器实际上会查看元素类型。)

【讨论】:

  • 很高兴有一些清晰,我接受了你的回答。现在由于这在以前的版本中运行良好(我的意思是代码不只是编译,它在运行时运行),应该有一些简单的解决方案来获得相同的行为?
  • 我会在我的回答中添加一点解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多