[swift-evolution] Treating an Enum's Cases as Its Subtypes
Matthew Johnson
matthew at anandabits.com
Mon Feb 20 09:32:17 CST 2017
> On Feb 20, 2017, at 12:40 AM, Niels Andriesse via swift-evolution <swift-evolution at swift.org> wrote:
>
> I'd like to discuss the possibility of treating the cases of a given enum as if they are subtypes of that enum. This seems like a natural thing to do because enum cases (especially when they have associated values) effectively define a closed set of subtypes.
>
> Doing so would allow for constructions such as the following:
>
> enum Foo {
> case a(name: String)
> }
>
> func isA(foo: Foo) -> Bool {
> // The old way:
> if case .a = foo { return true }
> return false
> // The new way:
> return foo is .a
> }
>
> func printNameIfFooIsA(foo: Foo) -> Bool {
> // The old way:
> if case let .a(name) = foo {
> print(name)
> }
> // The new way (1):
> if let a = foo as? .a {
> print(a.name <http://a.name/>)
> }
> // The new way (2):
> if let name = (foo as? .a)?.name {
> print(name)
> }
> }
>
> Treating an enum's cases as its subtypes would make enums easier to work with because handling them would be syntactically the same as handling other types.
>
> The pattern matching capabilities of enums wouldn't be affected by this proposal.
>
> Multiple other proposals have already attempted to simplify enum handling (they have particularly focused on getting rid of "if case" and adding the ability to treat enum case tests as expressions), but none of the solutions presented in those proposals have worked out so far.
>
> I believe that this could be the right solution to multiple enum-related problems that have been brought up repeatedly.
I would like to see enum cases treated as subtypes of the enum type. This is an interesting way to refer to the type of a case. Unfortunately I don’t think it will work if we accept the proposal to give cases a compound name. If we do that the name of this case becomes `a(name:)` which is not a valid type name.
My value subtyping manifesto discusses enum case types in detail. You may find it very interesting: https://gist.github.com/anandabits/5b7f8e3836387e893e3a1197a4bf144d
In the manifesto I show how the author of an enum can give the type a name distinct from the case name. I also discuss “anonymous case types”. The are necessarily anonymous because we have no valid type identifier to use for them (but we could have access to them dynamically when we have a value of the case type).
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170220/b339ce79/attachment.html>
More information about the swift-evolution
mailing list