Playground Damage for a Recursive Value Type

Xcode playgrounds for this code - if in the project it prevents compilation.

I am trying to declare only a very simple structure:

struct Node<T> { let value: T var next: Node<T>? init(_ value: T) { self.value = value next = nil } } 

If I do this on the Xcode playground, I get the following error message: The message with the playground service was unexpectedly interrupted.

If I declare this structure in a separate file in Xcode, the project cannot be compiled. All that I get in this case: Command failure due to signal: Segmentation error: 11.

Can someone help me? Is there a workaround? Any help is greatly appreciated.

+6
source share
1 answer

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

The linked list you are trying to execute holds a pointer or a link to the next node to the current node. Thus, each node has the same size. Swift structure, on the other hand, is not a reference type. The size of each node will differ depending on how many nodes it has to store recursively.

One way to achieve what you are trying to do with the structure is to use UnsafeMutablePointer . I do not need to warn you, because it quickly 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

+2
source

Source: https://habr.com/ru/post/976685/


All Articles