[swift-evolution] Treating an Enum's Cases as Its Subtypes
Joe Groff
jgroff at apple.com
Tue Feb 21 12:11:19 CST 2017
> On Feb 21, 2017, at 12:47 AM, Patrick Pijnappel <patrickpijnappel at gmail.com> wrote:
>
> Just to clarify, the proposal doesn't suggest to allow the associated value to be used as a subtype of the enum.
>
> enum Result<T> { case .success(T), .error(Error) }
>
> func foo(_ x: Result<Int>) { /* ... */ }
> func bar(_ x: Result<Int>.success) { /* ... */ }
>
> // Not this:
> foo(5)
> bar(5)
> // But rather:
> foo(.success(5))
> bar(.success(5))
>
> Effectively, Result<T>.success would behave like a struct that is a subtype of Result<T>.
I see. I would say that, like payload subtyping, having an independent type per case is sometimes useful, but not universally so. Result is in fact a good example of when you really don't want the cases to have independent type identity from the payloads, since there's really nothing interesting about "success" apart from T. "some" and "none" in an Optional or the different cases of JSON data similarly are just containers with no interesting meaning beyond being arms of an enum. If the cases are themselves types, that means they also need ABI layout rules, runtime type metadata, and other ceremony independent of the parent enum.
-Joe
More information about the swift-evolution
mailing list