简体   繁体   English

如何使用Swift 2.0声明递归枚举

[英]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. 我正在尝试在Swift 2中尝试递归枚举,但是我遇到了编译错误。

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: 所以,我从他们的WWDC15尝试了Apple自己的例子.Swift 的新内容是什么

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. 如果我创建一个新的游乐场并粘贴这些行,则会导致错误 - 请参阅屏幕截图,或者如果在Xcode项目中同样的话,请参阅其他截图。

I'm using Xcode 7.0. 我正在使用Xcode 7.0。

How come I can't even get Apple's example to compile? 为什么我甚至无法获得Apple的编译示例?

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

According to the release notes , support for this was added in Xcode 7 beta 4, which states: 根据发行说明 ,在Xcode 7 beta 4中添加了对此的支持,其中指出:

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: 以下代码适用于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. 有趣的是,尝试使用带有switch的枚举工作正常,但使用新的Swift 2 if case语法反复崩溃Xcode并使Playground无法使用。 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 beta1是最新版本。 Xcode 7 beta1—beta3 did not support this and their release notes contained the following verbiage: Xcode 7 beta1-beta3不支持这一点,他们的发行说明包含以下措辞:

“indirect” enum elements are not yet implemented yet in this beta, they will be added in a later update. “间接”枚举元素尚未在此测试版中实现,它们将在稍后的更新中添加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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