# Multiple Types

**URL:** <https://forums.swift.org/t/multiple-types/65023>\
**Category:** Pitches\
**Created:** [May 17, 2023, 12:48am UTC](https://forums.swift.org/t/multiple-types/65023 "2023-05-17T00:48:56Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![JCKL](https://avatars.discourse-cdn.com/v4/letter/j/dec6dc/32.png) [@JCKL](https://forums.swift.org/u/JCKL)\
**Post date:** [May 17, 2023, 12:48am UTC](https://forums.swift.org/t/multiple-types/65023/1 "2023-05-17T00:48:56Z")

</div>

Love to be able to do something like this:

var variable: String || Int  
func doSomething() -\> String || Int

The idea is that rather than using any you can keep better type constraints but be able to use a variable/return/etc. that has multiple constrained types.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [May 17, 2023, 1:35am UTC](https://forums.swift.org/t/multiple-types/65023/2 "2023-05-17T01:35:03Z")

</div>

Hi @JCKL, this is a [commonly rejected change](https://github.com/apple/swift-evolution/blob/main/commonly_proposed.md):

> - [Disjunctions (logical ORs) in type constraints](https://forums.swift.org/t/returned-for-revision-se-0095-replace-protocol-p1-p2-syntax-with-any-p1-p2/2855): These include anonymous union-like types (e.g. `(Int | String)` for a type that can be inhabited by either an integer or a string). "[This type of constraint is] something that the type system cannot and should not support."

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [May 17, 2023, 2:15am UTC](https://forums.swift.org/t/multiple-types/65023/3 "2023-05-17T02:15:45Z")

</div>

That's almost the same, no?

```swift
enum E {
    case string(String)
    case int(Int)
}

```

---

<div class="post-metadata">

**Author:** ![JCKL](https://avatars.discourse-cdn.com/v4/letter/j/dec6dc/32.png) [@JCKL](https://forums.swift.org/u/JCKL)\
**Post date:** [May 17, 2023, 2:29am UTC](https://forums.swift.org/t/multiple-types/65023/4 "2023-05-17T02:29:12Z")

</div>

That’s an interesting option. Thanks!

---

<div class="post-metadata">

**Author:** ![mgriebling](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mgriebling/32/29936_2.png) [@mgriebling](https://forums.swift.org/u/mgriebling)\
**Post date:** [May 22, 2023, 7:23am UTC](https://forums.swift.org/t/multiple-types/65023/5 "2023-05-22T07:23:52Z")

</div>

> [@JCKL](#):
>
> Love to be able to do something like this:
> 
> var variable: String || Int  
> func doSomething() -\> String || Int

Can you explain where this might be useful?

Swift currently supports tuples like `(s:String, i:Int)` which may also do what you need. When combined with optionals, you could mark which return parameter(s) are valid.

---

<div class="post-metadata">

**Author:** ![ExFalsoQuodlibet](https://avatars.discourse-cdn.com/v4/letter/e/bbce88/32.png) [@ExFalsoQuodlibet](https://forums.swift.org/u/ExFalsoQuodlibet)\
**Post date:** [May 22, 2023, 8:25am UTC](https://forums.swift.org/t/multiple-types/65023/6 "2023-05-22T08:25:56Z")

</div>

I'd love if the Core Team and/or the Language Steering Group reconsidered the absolute rejection of anonymous union types for Swift. Several modern languages are adopting them, they are objectively useful in many cases and, just to think of an example in Swift, they would enable ergonomic typed throws. For example, Richard Feldman in [this recent talk](https://www.youtube.com/watch?v=7SidSvJcPd0) shows how they can be leveraged for representing functional effects.

---

<div class="post-metadata">

**Author:** ![sveinhal](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/sveinhal/32/3992_2.png) [@sveinhal](https://forums.swift.org/u/sveinhal)\
**Post date:** [May 22, 2023, 10:09am UTC](https://forums.swift.org/t/multiple-types/65023/7 "2023-05-22T10:09:21Z")

</div>

> [@mgriebling](#):
>
> Can you explain where this might be useful?

Swift has support:

| Types | Product | Sum |
| --- | --- | --- |
| Named | `struct` | `enum` |
| Anonymous | tuple | _n/a_ |

For the sake of completeness it would be nice to have support for ad-hoc anonymous sum types.

---

<div class="post-metadata">

**Author:** ![Max\_Desiatov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/max_desiatov/32/20654_2.png) [@Max\_Desiatov](https://forums.swift.org/u/Max_Desiatov)\
**Post date:** [May 22, 2023, 2:58pm UTC](https://forums.swift.org/t/multiple-types/65023/8 "2023-05-22T14:58:22Z")

</div>

People requesting this feature should be careful what they wish for. I had extensive experience with anonymous sum types in TypeScript, and they effectively tend to make error messages completely unreadable. Good luck quickly finding a reason why your `A | B | C | D | E` value can't be passed to a function that expects `A | B | G | D | E` type. And I'm only using a single-letter types here to quickly write it out, in practice types have much longer names and can be generic with an arbitrary level of nesting (e.g. with result builders).

> [@sveinhal](#):
>
> For the sake of completeness it would be nice to have support for ad-hoc anonymous sum types.

Completeness should be always considered in the context of usability. Supporting something only because it allows us to cross off _n/a_ in some table just for the sake of it makes no sense if it tends to make developer experience worse on balance.

---

<div class="post-metadata">

**Author:** ![sveinhal](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/sveinhal/32/3992_2.png) [@sveinhal](https://forums.swift.org/u/sveinhal)\
**Post date:** [May 22, 2023, 3:03pm UTC](https://forums.swift.org/t/multiple-types/65023/9 "2023-05-22T15:03:28Z")

</div>

> [@Max\_Desiatov](#):
>
> they effectively tend to make error messages completely unreadable

Isn't that also true for tuples? I think if the types get sufficiently large, people will tend to create named types instead, just as large tuples, morph into structs as they mature, grow, or become used in many places.

Especially for single-use function arguments, it would often be useful for anonymous enums, methinks.

---

<div class="post-metadata">

**Author:** ![AlexanderM](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alexanderm/32/9781_2.png) [@AlexanderM](https://forums.swift.org/u/AlexanderM)\
**Post date:** [May 22, 2023, 3:44pm UTC](https://forums.swift.org/t/multiple-types/65023/10 "2023-05-22T15:44:02Z")

</div>

One of my highest voted answers on StackOverflow is exactly about this, on the question [Swift function returning two different types](https://stackoverflow.com/questions/40034034/swift-function-returning-two-different-types). The answer isn't _entirely_ wrong, but it's close.

I gave everyone the enum workaround, but it feels like I just gave out footguns. Strings and integers are almost nothing alike. A function that returns one or the other is _really weird_, and almost certainly indicative of a more basic data modelling issue that underpins it.

**Almost every time** I've seen someone reaching for union types (because it's a pretty natural spot to look for it), they had a situation that would be much better fixed by some combination of:

1. Picking a _single_ canonical data representation, and making everything else bridge to/from it.

2. Model the operations your return type needs to support, and represent them with a protocol. Anything that can conform to the protocol can work with it.

I think people have been reaching for this more since TypeScript got more popular, and I have to say, _even in TypeScript_, which has union types, they massively overused and cause some crazy code.

---

<div class="post-metadata">

**Author:** ![marcusrossel](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/marcusrossel/32/19160_2.png) [@marcusrossel](https://forums.swift.org/u/marcusrossel)\
**Post date:** [May 22, 2023, 4:02pm UTC](https://forums.swift.org/t/multiple-types/65023/11 "2023-05-22T16:02:37Z")

</div>

Doesn't an `Either` type satisfy that need?

---

<div class="post-metadata">

**Author:** ![sveinhal](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/sveinhal/32/3992_2.png) [@sveinhal](https://forums.swift.org/u/sveinhal)\
**Post date:** [May 22, 2023, 4:21pm UTC](https://forums.swift.org/t/multiple-types/65023/12 "2023-05-22T16:21:29Z")

</div>

> [@marcusrossel](#):
>
> Doesn't an `Either` type satisfy that need?

I guess if there was an `Either` type in the standard library, I might use it, just because it's there. But it always felt kinda awkward, and the case names are often not useful, like `.left` and `.right`. If I have to write the type myself, I might as well just create single-use ad-hoc enums for each situation. For function arguments, I might sometimes just create function overloads.

There are lots of other solutions and possible workarounds. I can design my way around it, create custom named types. No doubt. And as with every general tool, it can certainly be both used and misused.

But still, I think it would be nice to have the option to use anonymous sum types.

---

<div class="post-metadata">

**Author:** ![AlexanderM](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alexanderm/32/9781_2.png) [@AlexanderM](https://forums.swift.org/u/AlexanderM)\
**Post date:** [May 22, 2023, 5:27pm UTC](https://forums.swift.org/t/multiple-types/65023/13 "2023-05-22T17:27:25Z")

</div>

Could someone please steelman the case for when this might be useful, that wouldn't be better expressed with protocols?

The original example of `func doSomething() -> String || Int` isn't particularly compelling, without a better understanding of what `doSomething` might be that's reasonably implemented by returning a string or integer.

---

<div class="post-metadata">

**Author:** ![Dante-Broggi](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dante-broggi/32/7955_2.png) [@Dante-Broggi](https://forums.swift.org/u/Dante-Broggi)\
**Post date:** [May 22, 2023, 6:06pm UTC](https://forums.swift.org/t/multiple-types/65023/14 "2023-05-22T18:06:36Z")

</div>

One idea I’ve had that might make anonymous type unions (potentially) reasonably implementable is to require the user to provide the desired upper bound on the types. That is while:

```swift
T | U | ...

```

would not be a type,

```swift
(T | U | …) as V

```

where one can `as` cast from each of T, U, etc. into V, would be a type with the ABI of V and API of being composed solely of values which could have been derived from values of types T, U, etc. by `as` casting.

However, I haven't come across any occasions where this would be useful, and thus have not developed it further.

---

<div class="post-metadata">

**Author:** ![Tino](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tino/32/1073_2.png) [@Tino](https://forums.swift.org/u/Tino)\
**Post date:** [May 22, 2023, 6:33pm UTC](https://forums.swift.org/t/multiple-types/65023/15 "2023-05-22T18:33:17Z")

</div>

> [@AlexanderM](#):
>
> Could someone please steelman the case for when this might be useful, that wouldn't be better expressed with protocols?

Sure: Optionals.  
It is possible to model `Type?` as `Type|Null` ( [Ceylon (programming language) - Wikipedia](https://en.wikipedia.org/wiki/Ceylon_(programming_language)) did it that way).

Note that this choice has implications at the type level, which cannot be achieved with enums or an either-type — and those resolve some significant exceptions which Swift had to include for its optionals.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [May 22, 2023, 6:42pm UTC](https://forums.swift.org/t/multiple-types/65023/16 "2023-05-22T18:42:27Z")

</div>

> [@Tino](#):
>
> It is possible to model `Type?` as `Type|Null`

Unless I'm missing something, `Type|Null` can't represent nested optionality and as such wouldn't be able to substitute for Swift's `Optional` type.

---

<div class="post-metadata">

**Author:** ![Tino](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tino/32/1073_2.png) [@Tino](https://forums.swift.org/u/Tino)\
**Post date:** [May 22, 2023, 6:54pm UTC](https://forums.swift.org/t/multiple-types/65023/17 "2023-05-22T18:54:17Z")

</div>

> [@xwu](#):
>
> Unless I'm missing something, `Type|Null` can't represent nested optionality and as such wouldn't be able to substitute for Swift's `Optional` type.

That is true, but I don't see the difference as a downside (as it is unlikely that a 100% compatible reimplementation will ever be required).  
There is no real need for nested optionals, and afaics, in real world context, they are just annoying; see SE-230 for an example.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [May 22, 2023, 7:49pm UTC](https://forums.swift.org/t/multiple-types/65023/18 "2023-05-22T19:49:16Z")

</div>

> [@Tino](#):
>
> > [@xwu](#):
> >
> > Unless I'm missing something, `Type|Null` can't represent nested optionality and as such wouldn't be able to substitute for Swift's `Optional` type.
> 
> That is true

Is it not possible to have `(Type | Null) | Null` ?

> [@Tino](#):
>
> but I don't see the difference as a downside (as it is unlikely that a 100% compatible reimplementation will ever be required).

We could do this currently:

```swift
var dict: [String: String?] = ["hello" : nil]
if let element = dict["hello"] {
    if let value = element {
        print("has key and it is \(value)")
    } else {
        print("has key and it is nil")
    }
} else {
    print("has no key")
}

```

Without nested optionals I guess we'd rewrite it to smth like:

```swift
if dict.hasKey("hello") {
    if let value = dict["hello"] {
        print("has key and it is \(value)")
    } else {
        print("has key and it is nil")
    }
} else {
    print("has no key")
}

```

which doesn't seem a big deal. What other use cases we now have that require nested optionals and are there any show stoppers (i.e. something we can do now but it'll be impossible or too hard to do without nested optionals?)

---

<div class="post-metadata">

**Author:** ![Tino](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tino/32/1073_2.png) [@Tino](https://forums.swift.org/u/Tino)\
**Post date:** [May 22, 2023, 8:04pm UTC](https://forums.swift.org/t/multiple-types/65023/19 "2023-05-22T20:04:09Z")

</div>

> [@tera](#):
>
> Is it not possible to have `(Type | Null) | Null` ?

That would be `Type | Null | Null`, thus `Type | Null`.  
Of course, you could still have something like `Either<Type, Null> | Null`, but I don't think that is desirable.  
In the case of dictionary, I'd prefer a return type like `Missing | Value` which would result in `Missing | Type | Nil` when you really want to store `Type?`.

---

<div class="post-metadata">

**Author:** ![AlexanderM](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alexanderm/32/9781_2.png) [@AlexanderM](https://forums.swift.org/u/AlexanderM)\
**Post date:** [May 23, 2023, 12:19am UTC](https://forums.swift.org/t/multiple-types/65023/20 "2023-05-23T00:19:54Z")

</div>

> [@Tino](#):
>
> There is no real need for nested optionals, and afaics, in real world context, they are just annoying; see SE-230 for an example.

SE-230 is a bit of an exception, but there _absolutely_ is a real use for optionals. ("Need", not so much. But there's no "need" for `if` statements and `for` loops either, you _could_ just use `goto`)

Nested optionals can model the difference between "There is no value for your key in this dictionary" and "There is a value for your key, and it itself is actually `nil`".

As you point out, that can be modelled with `Missing | Type | Nil` as you suggested, but that's pretty much the JS solution of having `null` _and_ `undefined`. It leads to some weird edge cases, and is pointlessly artificially limited in a way that the nesting/composability of optionals isn't

[Next page](https://forums.swift.org/t/multiple-types/65023.md?page=2)
