15

I am trying to understand the exact limits on enums with generic associated values in Swift.

You might think that they are supported, since Optional is such a type. Here is the code defining Optional in the Swift standard library:

enum Optional<T> : Reflectable, NilLiteralConvertible {
    case None
    case Some(T)
// ...
}

It seems like the case member Some has an associated value of variable type T, right?

However, it is mentioned in the book Functional Programming in Swift (p 87), that such types are not supported:

We would like to define a new enumeration that is generic in the result associated with Success:

enum Result<T> {
    case Success(T)
    case Failure(NSError) 
} 

Unfortunately, generic associated values are not supported by the current Swift compiler.

And indeed, if you type that snippet into the compiler, you get an error (error: unimplemented IR generation feature non-fixed multi-payload enum layout).

So what is going on here? Is it just that it is not supported in general, but is supported for Optional as a special case? Is there any way to see how Optional receives this special support? Or if other standard library types also get special support?

2
  • 1
    It seems that an associated generic value is possible only if it is the only associated value.
    – Martin R
    Dec 2, 2014 at 19:49
  • Oh right. So in the error, "multi-payload" refers to there being more than once associated value. And what about "non-fixed"? I would guess that refers to the fact that the size of T is undetermined, since if it is a non-class type then it cannot be certainly known to have the size of an object pointer.
    – algal
    Dec 2, 2014 at 20:20

2 Answers 2

21

In Swift 2 (as part of Xcode 7), there is no limitation on associated values. So, feel free to dance to beats like this:

enum YouCanGoWith<T, U> {
    case This(T)
    case That(U)
    case Us
}

Now, if you're looking for a Success-or-Error kind of enum, you might want to stop and think about why... because Swift 2 also brings a new error handling model. So you don't need such a type as the return value of your functions — you can just declare it like so:

func walkWith(rhythm: Bool) throws -> Place { /* ... */ }

...and if your function succeeds, the caller always gets a (non-optional) Place for walken to. And — separately from using the result — the caller decides how to handle, swallow, or propagate the error.

For details on that, see Error Handling in The Swift Programming Language. Look closely — the syntax looks a bit like the exception model you see in some other languages, but Swift errors are an entirely different kind of animal.

(Of course, the throws model is specific to synchronous calls. If instead you're declaring callbacks for asynchronous processes, where the callback closure receives either the result of successful asynchronous work or an error — a Success-or-Error type is still entirely appropriate.)

7
  • My experience with playgrounds is that they don't always give you proper compiler errors. So something seeming to compile doesn't mean it's actually worked. You have to add some additional value at the end and make sure it really shows up with a value to prove the playground is running. That's doubly-true when you crash the compiler (which this kind of stuff still often does). I almost always do non-trivial work (read: everything) in little command-line apps because of that.
    – Rob Napier
    Dec 3, 2014 at 14:22
  • Failing to error and successfully running test cases are rather different, though. Nuked that part for now to avoid confusion.
    – rickster
    Dec 3, 2014 at 14:41
  • Sadly, though the compiler will allow you to declare the enum in this way, it won't let you bind it in a switch statement; I've tried a number of variations on switch result { case let .Success(data): ...}, all of which fail with the helpful (/s) warning "Command .../bin/swiftc failed with exit code 1". There are no further compiler warnings indicating which part of the pattern match causes the compiler to abort.
    – Scott R
    Jan 30, 2015 at 0:53
  • 1
    The compiler can't warn if it's crashing. File a bug!
    – rickster
    Jan 30, 2015 at 0:55
  • According to the swift programming language book, the throws keyword must precede the arrow. The example should be : func walkWith(rhythm: Bool) throws -> Place { /* ... */ }
    – Gael
    Jun 15, 2015 at 6:52
8

This answer is out of date in Swift 2. Please see rickster's answer for Swift 2 updates.

Your comments are correct. You can't have multiple cases with associated data if any of them have unknown size. Value types could be any size (since they're copied). Reference types (like objects) have a known size, because they store a pointer.

The typical solution to this is to create an extra wrapper class to hold the generic type, as the FP book does. Everyone calls it Box by convention. There's reason to hope that the Swift team will fix this in the future. As you note, they refer to it as "unimplemented" not "unsupported."

A typical implementation of Box:

final public class Box<T> {
  public let unbox: T
  public init(_ value: T) { self.unbox = value }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.