上QQ阅读APP看书,第一时间看更新
Recursive definitions
Some data structures need to be able to refer to instances of themselves within their own definition. You can't do this with a struct, but the lowly enum offers a solution.
Let's look at boxes that can contain either a number of books, or another box. We'll start by defining a Book type:
typealias Book = String
Yes, I know, the suggestion that a book is nothing more than a mere string of text is a little off the mark, but you know what I mean.
Next, we'll define a Box type, which can either contain Book objects (so an array of type [Book]), or another Box object:
enum Box
{
case books([Book])
case box(Box)
}
And straight away we get a compiler error.
However, this easily fixed, by declaring the .box case to be indirect:
enum Box
{
case books([Book])
indirectcase box(Box)
}
We can also declare the whole enum to be indirect, by placing the indirect keyword before the enum keyword: indirect enum Box.
Now we can have books in a box, or a box in a box, or a box of books in a box.