Hacker News new | ask | show | jobs
by wyager 3436 days ago
> Swift supports ADTs

True, but perhaps not practically relevant. The pattern matching in Swift isn't much better than what you would get with a tagged C union, which is why no one really uses it very heavily. The Optional type in Swift gets a lot of special compiler support, which is indicative of the fact that the broader language isn't very friendly towards using ADTs to structure data.

But you're right, I should have clarified in my comment that Swift does have a basic degree of support for ADTs.

3 comments

> The pattern matching in Swift isn't much better than what you would get with a tagged C union

In what way? Pattern matching in Swift is quite powerful; definitely better than C's switch statement. This blog post is a good overview of its capabilities. https://appventure.me/2015/08/20/swift-pattern-matching-in-d...

I don't know what kind of Swift code you're writing, but you're very, very wrong when you say "no one really uses it heavily". Pattern matching is in fact quite powerful and is used heavily in any codebase that isn't simply a straight porting of Obj-C idioms.

> The Optional type in Swift gets a lot of special compiler support

Only the ?. optional chaining operator (and technically the ! postfix operator too, though that could have been implemented in the standard library instead of being special syntax and in fact I'm not really sure why it isn't just a stdlib operator). And probably some logic in the switch exhaustiveness checker so it knows nil is the same as Optional.none. Everything else (including the actual pattern matching against the "nil" keyword) is done in a way that can be used by any type, not just Optionals (nil for pattern matching specifically evaluates to a stdlib type called _OptionalNilComparisonType which implements the ~= operator so it can be compared against any Optional in a switch, and you could do the same for other ADTs too, assuming they have a reasonable definition for nil).

In what way is Swift pattern matching not "much better than what you would get with a tagged C union"?

enum in Swift has pattern matching support, can have properties, adopt protocols, etc.

I would disagree with your assessment that "nobody uses them".