I created a recursive enumin Swift that compiles without errors or warnings, but which enters an infinite loop when I try to create it:
enum Tree<T> {
case Leaf(T)
case Branch(T, [Tree<T>])
}
Tree.Leaf(0)
Tree.Branch(0, [])
An infinite loop occurs when an instance is created, and not when printing or otherwise using an instance. Even if nothing is done with the result, Tree.Leaf(0)it still works forever. Just to be clear: an infinite loop occurs at runtime, not at compile time, but happens immediately after instantiation.
Oddly enough, the following very similar data structure works just fine:
enum WorkingTree<T> {
case Leaf(T)
case Branch([WorkingTree<T>])
}
WorkingTree.Leaf(0)
WorkingTree.Branch([.Leaf(1), .Leaf(2)])
Perhaps even stranger, the following data structure also works just fine:
enum ConcreteTree {
case Leaf(Int)
case Branch(Int, [ConcreteTree])
}
ConcreteTree.Leaf(0)
ConcreteTree.Branch(0, [])
, , ?
EDIT:
Swift REPL , , , "", . Swift REPL:
1> enum Tree<T> {
2. case Leaf(T)
3. case Branch(T, [Tree<T>])
4. }
5> Tree.Leaf(0)
. , :
1> enum Tree<T> {
2. case Leaf(T)
3. case Branch(T, [Tree<T>])
4. }
5. Tree.Leaf(0)
.
?
2:
. , :
enum Tree<T> {
case Leaf(T)
case Branch(T, [Tree<T>])
}
let test = Tree.Leaf(0)
print("Milestone 1")
switch test {
case .Leaf(_): print("Milestone 2")
default: print("This should never be called")
}
func no_op<T>(x: T) {}
no_op(test)
print("Milestone 3")
no_op(Tree.Leaf(0))
print("Milestone 4")
, no_op?