Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Swift中将类树转换为结构树_Swift_Algorithm_Tree - Fatal编程技术网

如何在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)
}

您需要遍历树并转换