[英]Swift: Array of any does not conform to protocol 'Decodable'
Decodable
协议需要一个带有解码器的初始化程序,如文档所述:
/// A type that can decode itself from an external representation.
public protocol Decodable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
init(from decoder: Decoder) throws
}
默认情况下,对于简单类型或其他可解码实现的类型,可以省略初始化程序,因为 Swift 可以自动将您的 JSON 对象映射到您的 Swift 对象。
在您的情况下, Any
类型不可解码:
Value of protocol type 'Any' cannot conform to 'Decodable', only struct/enum/class types can conform to protocols
因此,您应该使用特定的泛型类型(这是更好的解决方案)键入数组,或者在解码初始化程序中编写特定的解码过程:
public struct MyDecodable: Decodable {
public var id: Int
public var name: String
public var someData: [Any]
enum CodingKeys: String, CodingKey {
case id
case name
case someData
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
// Do your stuff here to evaluate someData from your json
}
}
更多信息在这里(Swift4): https ://medium.com/swiftly-swift/swift-4-decodable-beyond-the-basics-990cc48b7375
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.