Michael Welch
Michael Welch

Reputation: 1784

Why does this recursive Swift enum hang XCode?

If I enter the following code in a REPL or Playground or main project, it just hangs when it attempts to create the empty list.

import Cocoa


public final class Box<T> {
    private let _value : () -> T

    public init(_ value : T) {
        self._value = { value }
    }

    public var value: T {
        return _value()
    }

}

public enum List<U> {
    case Empty
    case Cons(U, Box<List<U>>)
}

var l = List<Int>.Empty;

I know this is a popular technique used to get around the fact that Swift doesn't let enums be truly recursive without some indirection (served by the Box class in this example).

I mean it's done here in this project, so I assume this works for some people.

I uninstalled and reinstalled XCode thinking somehow I had some "bad bits" left over from previous beta versions. Anyone else have this issue?

UPDATE 11/17/2015: Of course this question and answer are now obsolete. Please see how to define Recursive Enumerations here: Swift Programming Language - Enumerations

Upvotes: 0

Views: 210

Answers (1)

Michael Welch
Michael Welch

Reputation: 1784

Was working with someone on this and they resolved it.

https://github.com/typelift/swiftz/issues/114

https://github.com/typelift/swiftz/pull/120

The answer is to box the first parameter of Cons as well (you can use an autoclosure) like this Cons(@autoclosure () -> U, Box<List<U>>) and that will fix it. A rdar was filed.

Upvotes: 2

Related Questions