Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour for recursive enum in Swift (Beta 7)

Tags:

swift

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?

like image 643
Sam Avatar asked Dec 08 '22 06:12

Sam


1 Answers

It is worth noting that Swift 2 beta 2 and further has indirect keyword for recursive enum - that means

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

is valid language construct that doesn't break pattern matching in Swift 2.

TL;DR of the decision: "[…] we decided that the right solution is to simply not support general, non-obvious recursion through enums, and require the programmer to mediate that explicitly with indirect."


like image 131
mpolednik Avatar answered Dec 11 '22 07:12

mpolednik