我有一個想法,我正在嘗試測驗,我希望能夠擁有一系列不同的物件,這些物件都是可編碼的。
這是json
{
"cells":
[
{
"header": "dummy header"
},
{
"title": "dummy title"
}
]
}
還有一張來自 Firestore 的圖片,因為我不確定我是否正確地寫出了那個 json:

這是我迄今為止用泛型進行的測驗
struct Submission<Cell: Codable>: Codable {
let cells: [Cell]
}
struct ChecklistCell: Codable {
let header: String
}
struct SegmentedCell: Codable {
let title: String
}
首要目標是解碼具有可以是不同型別但都是可編碼的(單元格)陣列的檔案。我不確定這是否可行,或者是否有更好的方法。謝謝。
更新:
我做了@Fogmeister 的解決方案并讓它作業,但不是最理想的結果。它為理想情況下不存在的 json 添加了一個奇怪的層。有任何想法嗎?
uj5u.com熱心網友回復:
我過去做過類似的事情。不是使用 Firestore(盡管最近我做了),而是使用我們使用的 CMS。
正如@vadian 指出的那樣,Swift 不支持異構陣列。
還有……還有什么要指出的。
當你定義了一個泛型型別時......
struct Submission<Cell> {
let cells: [Cell]
}
然后,根據定義,cells是單一型別的同構陣列。如果您嘗試將不同的型別放入其中,它將無法編譯。
不過,您可以通過使用列舉將所有不同的 Cell 捆綁成一個型別來解決這個問題。
enum CellTypes {
case checkList(CheckListCell)
case segmented(SegmentedCell)
}
現在你的陣列將是一個同構陣列,[CellTypes]其中每個元素都是列舉的一個案例,然后將包含其中的單元格模型。
struct Submission {
let cells: [CellTypes]
}
這需要一些自定義解碼才能直接從 JSON 獲取,但我現在無法添加。如果您需要一些指導,我會更新答案。
編碼和解碼
從 JSON 的角度需要注意的事情。您的應用程式需要知道正在編碼/解碼的單元格型別。因此,您的原始 JSON 模式需要進行一些更新才能添加此內容。
您所展示的 Firestore 自動更新是一種相當常見的方法......
JSON 看起來有點像這樣......
{
"cells":
[
{
"checkListCell": {
"header": "dummy header"
}
},
{
"segmentedCell": {
"title": "dummy title"
}
}
]
}
Essentially, each item in the array is now an object that has a single key. From checkListCell, segmentedCell. This will be from any of the cases of your enum. This key tells your app which type of cell the object is.
Then the object shown against that key is then the underlying cell itself.
This is probably the cleanest way of modelling this data.
So, you might have two checklist cells and then a segmented cell and finally another checklist cell.
This will look like...
{
"cells":
[
{
"checkListCell": {
"header": "First checklist"
}
},
{
"checkListCell": {
"header": "Second checklist"
}
},
{
"segmentedCell": {
"title": "Some segmented stuff"
}
},
{
"checkListCell": {
"header": "Another checklist"
}
},
]
}
The important thing to think when analysing this JSON is not that it's harder for you (as a human being) to read. But that it's required, and actually fairly easy, for your app to read and decode/encode.
Hope that makes sense.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/311153.html
上一篇:Swift中關于不透明回傳型別和關聯型別協議的一些問題
下一篇:轉到通用頻道型別
