簡體   English   中英

Swift:任何數組不符合“可解碼”協議

[英]Swift: Array of any does not conform to protocol 'Decodable'

我正在解碼一個 json 響應,但我得到了不同對象的數組。 這是我的實現:

public struct MyDecodable: Decodable {
    public var id: Int
    public var name: String
    public var someData: [Any]
}

這是我的錯誤:

在此處輸入圖片說明

我對你們中的任何人的問題是,我怎樣才能使這個實現符合可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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM