Hacker News new | ask | show | jobs
by coolsunglasses 4161 days ago
>One of my favorite parts of Swift is the optional concept

What if you need the fallback value to be an error possessing information about what went wrong?

    data Maybe a = Just a | Nothing

    data Either a b = Left a | Right b
3 comments

Swift's Optional is just Maybe with some built-in sugar. Sum types are supported, with the caveat that the compiler is sort of broken when it comes to generics.

Personally, I just want higher-kinded types, and for the following code snippets to work as-is:

  enum Either<A,B> {
    case Left(A)
    case Right(B)
  }

  enum Tree<A> {
    case Leaf
    case Node(Tree<A>, A, Tree<A>)
  }
The first breaks because of the "Unimplemented non-fixed multi-payload enum layout" compiler error, and the second breaks because enums have value semantics. Both can be worked around in full generality by declaring a 'Box<T>' generic wrapper class, but that workaround is inelegant and cumbersome.
I agree! Eithers are cool, too. What I'm really excited about is that these sorts of concepts are starting to find their way into languages like Swift. Getting built-in support for Eithers would be super awesome.

In the meantime, you can vaguely simulate it with named tuples.

  let response = (error: "Could not connect to server", success: false)

It's not quite the same, but at least there's an easy way to bundle your data together.

edit: I like Someone's suggestion to use and discussion about using enums as union types below.

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.
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.
> Getting built-in support for Eithers would be super awesome.

Wait, what? Swift has sum types (ie. enums), so there's no need for it to be built in.

Use Swift's nil coalescing operator: a ?? b