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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With