【发布时间】:2018-06-05 18:50:02
【问题描述】:
问题:我正在尝试解码我的 JSON,其中一些 JSON 将具有随机字符串,而另一些将具有硬编码字符串。当硬编码字符串是以下之一时,我想显示不同的 UICollectionView 单元格。如果我的 JSON 是硬编码字符串并且能够用它显示不同的 UICollectionViewCell,我在尝试解析我的 JSON 时遇到问题。对此的任何帮助都会很棒。这可能是一个初学者的问题,但我在过去一周试图解决这个问题,但我很难做到。对此的任何帮助将不胜感激。
** Hardcoded Strings that could be one or the other:**
key: --> This string could be "breaking" or "normal" or "new"
item: --> This string could be "placement" or "slot" or "shared"
verb: --> This string could be "shared" or "posted"
** NOT hardcoded strings, which the string comes in randomly**
heading: --> This string is a random string
type: --> This string is a random string
这是我的一些 JSON,因此您可以获取我正在尝试做的示例:
{
slots: [
{
key: "breaking",
item: "placement",
heading: "Random String Text",
type: "Random String Text",
via: "Random",
verb: "shared"
sort_order: 0
},
{
key: "breaking",
item: "placement",
heading: "Random String Text",
type: "Random String Text",
via: "Random",
verb: "posted"
sort_order: 1
},
{
key: "event",
item: "combine",
heading: "Random String Text",
type: "Random String Text",
via: "Random",
verb: "posted"
sort_order: 2
},
}
这是我迄今为止为我的模型所做的:
struct MyModel: Decodable {
var key: String?
var item: String?
var heading: String?
var type: String?
var via: String?
var verb: String?
}
这是 Dmitry Serov 帮助我完成的一个示例单元格。
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let model = ... // retrieve your model object here
if model.verb == .shared {
// Pass the pertinent identifier
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:...)
return cell
else {
....
}
}
这是 Dmitry Serov 帮助我编写的更多代码。
struct MyModel { // Type names should use pascal case in Swift
var verb: State?
....
enum State {
case shared
case posted
}
}
// Decode your enums from strings
extension MyModel.State: Decodable {
enum CodingKeys: String, CodingKey {
case shared
case posted
}
}
当我尝试上面的问题时,它要求我输入下面的格式,我不知道该怎么做,我正在尝试解析更多的键。
extension MyModel.State: Decodable {
init(from decoder: Decoder) throws {
}
}
【问题讨论】: