【发布时间】:2018-10-21 20:06:24
【问题描述】:
鉴于Array 符合Codable,我假设Codable 的数组,即[Codable] 肯定可以转换为Codable。
我用Decodable 部分做了一个简单的例子。只是为了验证:
// Attempt to conform Array to Decodable
extension Array : Decodable { }
这会导致警告:Conformance of 'Array<Element>' 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<Swift.Decodable>' (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<Decodable>表示Array,其中Element是Decodable。扩展只是为了证明 Array 确实已经符合Decodable,正如您所指出的,它的要求是其Element泛型符合Decodable。
标签: arrays swift codable swift4.2