簡體   English   中英

Swift和Codable:以可遵循自定義協議的值終止的可編碼樹結構

[英]Swift and Codable: Encodable tree struct terminating in values that obey custom protocol

我試圖使樹數據結構服從可編碼協議。 樹終止於服務於“終端”協議的“某個對象”。 終端擴展了Codable。

樹的每個節點都是一對。 它有一個鍵和一個值。 值可以是一對,也可以是終端。

有兩個主要問題:

1)我希望這個結構能夠編碼為JSON

class Pair: Codable {
   var key: String?
   var value: Codable?
}

let outputSimple = Pair(key: "a test key", value: "a test value")
// encodes to
// {"a test key": "a test value"}
// whereas currently encodes to
// {}

let outputComplex = Pair(key: "a parent", value: Pair(key: "another pair", value: "a test value"))
// encodes to
// {"a parent": {"another pair", "a test value"}}

編輯:第2部分可能會略微混淆問題。 為了澄清上面的問題,如果我有

class Pair: Codable {
   var key: String
   var value: String
}
let p = Pair(key:"foo", value: "bar")

我怎么能輸出{“foo”:“bar”}而不是{key:foo,value:bar}? 我試過了

    override func encode(to encoder: Encoder) throws {
        var container = encoder.unkeyedContainer()
        container.encode(contentsOf: [key: value])
    }

但得到錯誤“實例方法'編碼(contentsOf :)'要求'(key:_,value:_)'符合'Encodable'”

2)我正在嘗試以下但它似乎不起作用。 我得到“配對不符合協議'可解碼'”

protocol TreeNode: Codable {} 
struct Pair: TreeNode {
   var key: String?
   var value: TreeNode?
}

extension String: TreeNode {}

我可以通過使TreeNode成為具有Pair子類的類來解決這個問題。 這也可能是正確的Swift行為。 但是,我想知道是否有更多的眼睛可以解釋這個問題。 我假設只要我確保所有值都是類型對,或其他服從Codable的值,那么它就可以工作。

這不行。

value必須是符合Codable的具體類型,而不是協議本身或符合Codable的第二個協議

你可以做的是將value聲明為通用value

class Pair<T: Codable>: Codable {
    var key: String?
    var value: T?

    init(key: String?, value: T?) {
        self.key = key
        self.value = value
    }
}

它可以編碼outputSimpleoutputComplex

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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