[swift-evolution] [Draft] Anonymous Enum Cases

Daniel Duan daniel at duan.org
Wed Mar 8 21:09:34 CST 2017

Hi all,

During review for the first revision of SE-0155, Dave Abraham suggested that we should allow enum cases without base names. So here’s a (rough) draft of a proposal for this feature. Please read and share your thoughts!

# Anonymous Enum Cases

* Proposal: [SE-NNNN](NNNN-anonymous-enum-cases.md)
* Authors: [Daniel Duan](https://github.com/dduan)
* Review Manager: TBD
* Status: **Awaiting review**

## Introduction

This proposal adds anonymous cases to Swift's enum.

## Motivation

Naming things is a tough task for programmer. This is one merit of features such
as anonymous function and tuples: users can use them in a limited scope and skip
the mind burden of coming up with names. We can expand this convenience to enums
by allowing user to declare, construct and pattern match anonymous cases.

## Proposed solution

Add anonymous cases to Swift's enum.

## Detailed design

Anonymous enums can be declared with this syntax:

enum Foo {
    case (Int)
    case (label0: Int, label1: String)

Anonymous case without any associated values is not allowed.

Anonymous case values can be constructed with constructors with the enum's name
being their base name. Following the example:

Foo(42) // constructs `Foo` case corresponding to `case (Int)`
Foo(label0: 0, labe1: "hello") // value of type Foo, 2nd case.
Foo(label0: label1:)(0, "hello") // constructs the same value, SE-0155 syntax

For pattern matching, rules remain the same as regular cases, execpt, naturally,
the base name shall be skipped.

case .(let x) = Foo(42) // x has value 42
case .(label0: let a, label1: let b) = Foo(label0: 0, label1: "hello") // ok

## Source compatibility

This is additive. It's fully source compatible with Swift 3.

## Effect on ABI stability

This feature adds new possibilities to symbols exposed by enum declarations.

## Effect on API resilience

## Alternatives considered

It may seem "regular" to make user use `_` in place of base name in
declarations. The author think that's a perspective that only makes sense for
language designer/compiler implementors. To a user, the syntax chosen in this
proposal is clear and succinct.

More information about the swift-evolution mailing list