[英]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.