简体   繁体   中英

How to declare recursive enums with Swift 2.0

I'm trying to experiment with recursive enums in Swift 2 however I'm getting compilation errors.

I started off trying to define my own example:

enum Tree {
    case Empty
    indirect case Node(value: Int, left: Tree, right: Tree)
}

But get an error: "Consecutive declarations on a line must be separated by :".

So, I tried Apple's own example from their WWDC15 What's New in Swift presentation:

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

But its the same compilation error with this also. If I create a new playground and paste these lines in then it results in the error - see screenshot, or if in an Xcode project same thing, see other screenshot.

I'm using Xcode 7.0.

How come I can't even get Apple's example to compile?

在此输入图像描述在此输入图像描述

According to the release notes , support for this was added in Xcode 7 beta 4, which states:

Enums and cases can be marked indirect, which causes the associated value for the enum to be stored indirectly, allowing for recursive data structures to be defined.

The following code works in a Playground:

enum Tree {
    case Empty
    indirect case Node(value: Int, left: Tree, right: Tree)
}

let tree1 = Tree.Node(value: 0, left: Tree.Empty, right: Tree.Empty)
let tree2 = Tree.Node(value: 0, left: Tree.Node(value: -1, Tree.Empty, Tree.Empty), right: Tree.Empty)

Anecdotally, trying to use the enum with a switch worked fine, but using the new Swift 2 if case syntax repeatedly crashed Xcode and made the Playground unusable. I'm not sure if this is related specifically to enums or just general beta instability.


Background:

At the time this question was originally asked and this answer accepted, Xcode beta1 was the latest release. Xcode 7 beta1—beta3 did not support this and their release notes contained the following verbiage:

“indirect” enum elements are not yet implemented yet in this beta, they will be added in a later update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM