[swift-evolution] [Pre-Proposal-Discussion] Union Type - Swift 4
matthew at anandabits.com
Sat Aug 20 11:35:46 CDT 2016
> On Aug 20, 2016, at 10:36 AM, Haravikk <swift-evolution at haravikk.me> wrote:
>> On 19 Aug 2016, at 15:38, Xiaodi Wu via swift-evolution <swift-evolution at swift.org> wrote:
>> Ad-hoc enums have been discussed already, at length, and all the weaknesses touched on then still apply now. For instance, since they're ad-hoc, can you pass an instance of type "Int | String" as an argument if the function expects a "String | Int | Float"? Enums don't have duck typing behavior like that; if your ad-hoc type does, then it's not very much like an enum; if it doesn't, it won't feel much like a union type.
> While ad-hoc enums are certainly similar I don't think that this problem applies to unions; the problem with ad-hoc enums is that while cases may have the same name, the meaning of a case may not be identical, so compatibility is uncertain. For type unions I'd say this isn't an issue; I'd say that yes, String | Int is compatible with String | Int | Float as every possible value can be carried over (whereas the reverse is not true), they're just values of one of several types, so as long as the conversion is possible, it should be fine to pass it on (or rather, repackage it behind the scenes).
>> Moreover, an ad-hoc "String | Int" may look like a union type, but until switching over an instance to cast it, you can't invoke any methods common to String and Int. So it really doesn't feel like a union type at all.
> Could it not do that though? I'd say that a union type should conform to any common protocols that its members conform to; if this can be done in the initial release then great, otherwise it can come later.
Conforming to common protocols would be much better than an implicit ad-hoc / duck-typed protocol that simply exposes all common members. But there is strong opposition to unions, much of which is related to implementation complexity. It seems to me that the path to having unions or a union-ish feature receiving serious consideration is to demonstrate the value they can offer even with relatively restricted functionality (such as syntactic sugar for enums with implicit lifting). If that is successful we will have an opportunity to work with them and make a case for enhancements in the future.
Also, it won't always possible for a union to conform to a protocol conformed to by all member types. If the protocol has `Self` requirements in argument position it would not be able to conform and if it has associated type requirements which are bound to different concrete types in the types making up the union it would also not be able to conform.
More information about the swift-evolution