【问题标题】:Indirect Enum or Class, Which One Should I Use for Building Basic Data Structures间接枚举或类,我应该使用哪个来构建基本数据结构
【发布时间】:2015-11-17 09:14:40
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: algorithm swift data-structures swift2


    【解决方案1】:

    好吧,不管它是 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 和数据结构的更多示例,请访问: data structures swift

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

    【讨论】:

      猜你喜欢
      • 2011-03-08
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多