[swift-evolution] [Pre-Proposal-Discussion] Union Type - Swift 4

David Sweeris davesweeris at mac.com
Sat Aug 20 11:15:36 CDT 2016


> On Aug 20, 2016, at 10:36, Haravikk via swift-evolution <swift-evolution at swift.org> 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.

This exact scenario came up in the context of iterating over the members of a heterogeneous tuple. If I wasn't on my phone, I'd find a link to the relevant posts, but IIRC the gist of it is (my wording) "it doesn't work that way", or at least not without a *lot* of work and a high load on the type-checker.

- Dave Sweeris


More information about the swift-evolution mailing list