我试图在swift中创建一个通用树。我编译的代码,但在运行时卡住了。节点通过其父和子属性引用自身,就像任何树应该一样。但这些使得迅速窒息。那么你应该如何使用泛型代表一棵树呢?我发现了很多早期测试版的问题和尝试,但最近没有。
protocol TreeNodeProtocol
{
typealias LeafType : Comparable
var representedObject : LeafType { get set }
var parent : Self? { get set }
var children : [Self]? { get set }
}
final class TreeNode<LeafType : Comparable> : TreeNodeProtocol, Comparable
{
var parent : TreeNode? = nil
var children : [TreeNode]? = nil
var representedObject : LeafType
init(representedObject : LeafType)
{
self.representedObject = representedObject
}
}
func == <LeafType: Comparable> (left : TreeNode<LeafType>, right : TreeNode<LeafType>) -> Bool
{
return left.representedObject == right.representedObject
}
func < <LeafType: Comparable> (left : TreeNode<LeafType>, right : TreeNode<LeafType>) -> Bool
{
return left.representedObject < right.representedObject
}
class Tree<LeafType : Comparable>
{
typealias TreeNodeType = TreeNode<LeafType>
var description : String { return "a Tree" }
var rootNodes : [TreeNodeType] = []
func insertRootNode(node : TreeNodeType, atIndex index: Int? = nil)
{
let assumedIndex = index ?? rootNodes.count
assert(assumedIndex <= rootNodes.count, "Tree: index exceeds bounds")
rootNodes.insert(node, atIndex: assumedIndex)
}
func insertRootNode(representedObject : LeafType, atIndex index: Int? = nil)
{
let newRootNode = TreeNodeType(representedObject: representedObject)
let assumedIndex = index ?? rootNodes.count
assert(assumedIndex <= rootNodes.count, "Tree: index exceeds bounds")
rootNodes.insert(newRootNode, atIndex: assumedIndex)
}
}
let aTree = TreeNode<String>(representedObject: "d") //it doesn't go past this point
println(aTree)
另一个问题是,我无法使Tree引用TreeNodeProtocol而不会生成编译器错误,因为它具有关联类型。