如何在Swift中将类树转换为结构树
我有以下两种类型如何在Swift中将类树转换为结构树,swift,algorithm,tree,Swift,Algorithm,Tree,我有以下两种类型 class Node { var title: String var children: [Node]? } struct Section { let title: String let subsections: [Section] } 我有一个具有多个根的节点树。也就是说,一个[节点]数组。 我想将此树转换为另一个[Section] 如何执行此操作?如果存在[Node]数组,则可以按如下方式转换为结构数组: func getTreeOfSe
class Node {
var title: String
var children: [Node]?
}
struct Section {
let title: String
let subsections: [Section]
}
我有一个具有多个根的节点树。也就是说,一个[节点]
数组。
我想将此树转换为另一个[Section]
如何执行此操作?如果存在
[Node]
数组,则可以按如下方式转换为结构数组:
func getTreeOfSections(nodes: [Node]) -> [Section] {
var sections = [Section]()
for node in nodes {
let section = getSection(from: node)
sections.append(section)
}
return sections
}
func getSection(from node: Node) -> Section {
let title = node.title
var subsections = [Section]()
for child in node.children {
let subsection = getSection(from: child)
subsections.append(subsection)
}
return Section(title: title, subsections: subsections)
}
您需要遍历树并转换