Strange behavior for recursive enumeration in Swift (beta 7)

enum Tree{
    case Leaf(String)
    case Node(Tree)
} //compiler not happy!!

enum Tree{
    case Leaf(String)
    case Node([Tree])
} //compiler is happy in (arguably) a more complex recursive scenario?

How can the Swift compiler work for the second (more complex) scenario, and not the first?

+4
source share
3 answers

The type of value (enumeration) cannot contain itself as a direct member, since it does not matter how large the data structure is, it cannot contain itself. Apparently, the related data on the cases of the transfer are considered as direct members of the transfer, therefore the related data cannot be the type of the transfer itself. (In fact, I want them to do recursive correspondence, which would be so great for functional data structures.)

, , . , ( ), , . , (, , ), .

: [Tree] Tree . Array , , Array, Array<T>, .

+3

, Swift 2 beta 2 indirect -

enum Tree<T> {
    case Leaf(T)
    indirect case Node(Tree)
}

, Swift 2.

TL; DR : "[...] , , , enums , ".


+10

( Swift) Apple,

"box" (, ).

However, the following code (which works in Swift 1.1) does not work in Swift 1.2, which comes with Xcode Beta Version 6.3 (6D520o). The error message “Attributes can only be applied to declarations, not to types”, however, if it is intended, I don’t know how to reconcile it with Lattner’s statement about the behavior that he mentioned in the previous quote as “useful and we don’t removed it with Swift 1.2. "

enum BinaryTree {
    case Leaf(String)
    case Node(@autoclosure () -> BinaryTree, @autoclosure () -> BinaryTree)
}

let l1 = BinaryTree.Leaf("A")
let l2 = BinaryTree.Leaf("B")
let l3 = BinaryTree.Leaf("C")
let l4 = BinaryTree.Leaf("D")
let n1 = BinaryTree.Node(l1, l2)
let n2 = BinaryTree.Node(l3, l4)
let t = BinaryTree.Node(n1, n2)
+1
source

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


All Articles