Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playground crashes for Recursive Value Type

Xcode playground crashes for this code - if in project it prevents compilation.

I am trying to declare just a very simple struct:

struct Node<T> {
    let value: T
    var next: Node<T>?

    init(_ value: T) {
        self.value = value
        next = nil
    }
}

If I do that in XCode playground I get following error message: The Communication with the playground service was interrupted unexpectedly.

If I declare this struct in separate file in XCode the project cannot be compiled. All I get is in this case Command failed due to signal: Segmentation fault: 11.

Can somebody help me with this? Is there a workaround? Any help very much appreciated.

like image 741
Rasto Avatar asked Oct 13 '14 19:10

Rasto


1 Answers

Quoting the swift documentation, "Structures are always copied when they are passed around in your code, and do not use reference counting." [1]

A linked list that you are trying to achieve works by storing a pointer or reference to the next node on the current node. This way, each node has the same size. Swift's struct on the other hand are not reference type. The size of each node will be different depending on how many nodes it has to store recursively.

One way to achieve what you are trying to do with struct is using UnsafeMutablePointer. I don't need to warn you because doing this in swift makes you write "unsafe" every few lines.

struct Node<T> {
    var x: T
    // Setting pointer type to <Node<T>> compiles, but infinite loops on runtime (Swift 1.2)
    var next: UnsafeMutablePointer<Void>
}

var second = Node(x: 2, next: nil)
var first = Node(x: 1, next: &second)

print(unsafeBitCast(first.next, UnsafeMutablePointer<Node<Int>>.self).memory.x) // Prints 2

[1] https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html

like image 105
Hendrik Poernama Avatar answered Nov 04 '22 00:11

Hendrik Poernama