你好,我遇到这样的情况:
(
{
"Nov 2018" = {
AudioFileURL = "https://www.GeorgeA.m4a";
AudioFileText = "GeorgeA";
};
},
{
"Nov 2018" = {
AudioFileURL = "https://www.GeorgeB.m4a";
AudioFileText = "Georgeb";
};
},
{
"Nov 2018" = {
AudioFileURL = "https://www.Georgec.m4a";
AudioFileText = "Georgec";
};
},
{
"Sep 2018" = {
AudioFileURL = "https://www.GeorgeB.m4a";
AudioFileText = "GeorgeD";
};
}
)
现在,我想将所有Values与同一个键组合在一起,以便可以在带有UITableView controller的部分中使用它们。有人可以为我提供一些指导吗。
我正在寻找的输出是这样的
(
{
"Nov 2018" = {
[AudioFileURL = "https://www.GeorgeA.m4a";
AudioFileText = "GeorgeA"],
[AudioFileURL = "https://www.GeorgeB.m4a";
AudioFileText = "GeorgeB"],
[AudioFileURL = "https://www.GeorgeC.m4a";
AudioFileText = "GeorgeC"];
};
},
{
"Sep 2018" = {
[AudioFileURL = "https://www.GeorgeB.m4a";
AudioFileText = "GeorgeD";]
};
}
)
答案 0 :(得分:0)
首先在一个单元格中构建一个表示所需信息的结构:
struct AudioFileInfo {
let urlString: String
let text: String
init(dict: [String: String]) {
urlString = dict["AudioFileURL"] ?? ""
text = dict["AudioFileText"] ?? ""
}
}
struct CellInfo {
let date: String
let audioFileInfos: [AudioFileInfo]
}
然后您可以:
let cellInfos = response
.flatMap {
$0.map { ($0.key, AudioFileInfo(dict: $0.value)) }
}
.reduce([CellInfo]()) { partial, item in
var new = partial
if let index = partial.index(where: { $0.date == item.0 }) {
new[index] = CellInfo(date: partial[index].date, audioFileInfos: partial[index].audioFileInfos + [item.1])
}
else {
new.append(CellInfo(date: item.0, audioFileInfos: [item.1]))
}
return new
}
这将为您提供CellInfo对象的数组。
通常,这是解决此类问题的方式。首先定义一个代表所需输出的类型,然后操纵输入,直到创建该类型的对象。游乐场是您做这种事情的朋友。
答案 1 :(得分:0)
类似的事情将为您服务
typealias AudioFile = (url: String, text: String)
class DictArray {
var items: [MainModal]
class MainModal {
let date: String
var files: [AudioFile]
init(key: String, file: AudioFile) {
self.key = key
self.files = [file]
}
}
init(dictArray: [[String: [String: String]]]) {
for dict in dictArray {
if let date = dict.keys.first {
if let item = items.first(where: { $0.date == date }) {
guard let value = dict.values.first as? [String: String] else { continue }
let file = AudioFile(url: value["AudioFileURL"]!, text: value["AudioFileText"]!)
item.files.append(file)
} else {
guard let value = dict.values.first as? [String: String] else { continue }
let file = AudioFile(url: value["AudioFileURL"]!, text: value["AudioFileText"]!)
items.append(MainModal(key: date, files: [file]))
}
}
}
}
}
DictArray(dict: json)