Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Swift's enums are like Rust's enums, so they're much more powerful than C's enums:

In C an enum can assume one of multiple predefined values of type `int`.

In Swift an enum can work like that too, but it can also assume values of types other than int. This is similar to the behavior of the unions in C, but more high level, with proper safety checks in place.

In Swift enums can also have methods, so there are two methods to return fields from the values contained in the enum —regardless of the actual type being held at that time.



The computer science name for that is sum type, the (or maybe just the simplest) implementation a tagged union (maybe I'm making up that distinction; Wikipedia thinks they are synonyms (http://en.wikipedia.org/wiki/Sum_type)). You can do ~the same~ in C with a struct and an union:

    typedef sruct s
    {
      int type;
      union
      {
        int i;
        float f;
        double d;
      } value;
    }
But there, it is up to you to make sure that you only read the int/float/double if the 'type' field indicates a int/float/double was stored. Higher-level languages enforce that you can only read the union as being of type T if you wrote it as type T.


  case let .DoubleCombine(s, _, _): return s
Is the underscore a special character in this case to tell the compiler not to read in the value of those arguments? Or is it actually loading in "second" and then "value" into an argument named _?


Assuming it's the same as other pattern matching langs it is a wildcard that signals the intent that you don't care about what value those would be.


And the functions there are examples of pattern matching in Swift.

To the GP. That code example is a very good example of just how different Swift code be from Objective-C.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: