间接枚举或类,我应该使用哪一个来构建基本数据结构



当我尝试在Swift 2中实现一些基本的数据结构,如链接/双链接/循环链接/循环双链接列表、AVL树、红黑树、b树和Treap时,我决定利用Swift 2的新特性:间接枚举来做这些事情,因为枚举使空节点和填充节点比类更具语义性。

但很快就发现,对于非循环链表,在插入元素之后返回插入的节点是没有意义的,因为返回的值是值类型而不是引用类型。据说不能通过直接向返回值写入信息来加速下一次插入,因为它是插入节点的副本,而不是对插入节点的引用。

更糟糕的是,改变一个基于间接枚举的节点意味着写入关联值的整个数据簇,这肯定会引入不必要的系统资源消耗,因为每个枚举情况下的关联值本质上是一个元组,本质上是一种内存中的连续数据,它与结构体相同,但没有每个属性访问器来实现小数据簇的写入。

那么我应该使用哪一个来构建这样的基本数据结构呢?间接枚举还是类?

这与swift 1或swift 2无关,因为目前EnumStructuresvalue类型,而Classes是通过引用调用的。因为你想在你的代码中使用数据结构,就像你自己调用它一样,按值调用它们是不好的。你将不得不使用Class,以便你的代码做你想做的事情。下面是一个使用Class:

的链表示例
      class LLNode<T> 
    {
    var key: T? var next: LLNode? var previous: LLNode? 
    } 
          //key printing
        func printAllKeys() 
    {
     var current: LLNode! = head; //assign the next instance 
    while(current != nil) 
    {
     println("link item is: (current.key)") 
     current = current.next 
    } 
    }
public class LinkedList<T: Equatable> 
{ //create a new LLNode instance private 
var head: LLNode<T> = LLNode<T>() //append a new item to a linked list 
func addLink(key: T) 
{ //establish the head node 
if (head.key == nil) 
{ 
head.key = key;
return; 
} //establish the iteration variables 
var current: LLNode? = head 
while (current != nil) 
{ 
if (current?.next == nil) 
{ 
var childToUse: LLNode = LLNode<T>() 
childToUse.key = key; 
childToUse.previous = current 
current!.next = childToUse; 
break; 
}
 current = current?.next 
} //end while 
} ///end function 
有关swift和数据结构的更多示例,请访问:数据结构swift

结论:如果你想通过引用调用,请使用Class,否则请使用EnumStruct

相关内容

最新更新