Hacker News new | ask | show | jobs
by Someone 4159 days ago
Other approach: use enums as union types. From https://developer.apple.com/library/ios/documentation/Swift/...:

  enum Barcode {
    case UPCA(Int, Int, Int, Int)
    case QRCode(String)
  }
This can be read as:

“Define an enumeration type called Barcode, which can take either a value of UPCA with an associated value of type (Int, Int, Int, Int), or a value of QRCode with an associated value of type String.”

So, you can do

  enum ResultOrError {
    case Result(ReturnValue)
    case Error(int,String)
  }
Unfortunately, enums and generics do not mix, AFAIK, so it looks clumsy.

I think the reason for the special syntax of '?.' is that the designers think it is a very common case, at least in Swift programs.

And yes, I would like to see a better syntax for that, too. A generalization of C's short-hand 'if'

   flag ? trueExpression : falseExpression;
For switch statements would be cool.
1 comments

Enums and generics mix just fine in theory. Rust is a good example of this, with the `Result<T,E>` type. But at the moment in Swift if you try this you get "error: unimplemented IR generation feature non-fixed multi-payload enum layout". Presumably this will be supported at some point.