自己项目中遇到的一个实际问题,想了两天总算想出来了,现在记录备忘下:
func rawModelsToTree(rawModels: [Model], rootNode: String, parentNode: String, childrenNode: String) -> [Model] {
// 0. 创建根节点
let rootModels = rawModels.filter { $0.pId == rootNode }
for model1 in rawModels {
// 1. 配置根节点
for rootModel in rootModels {
if rootModel.id == model1.pId {
rootModel.subModel.append(model1)
}
}
// 2. 配置子节点
for model2 in rawModels {
// 2.1 之前配置过的根节点排除
guard rootModels.contains(model1) == false && rootModels.contains(model2) == false else { continue }
if model1.id == model2.pId { // model1是model2的父
model1.subModel.append(model2)
} else if model2.id == model1.pId { // model1是model2的子
model2.subModel.append(model1)
}
}
}
return rootModels
}