# Extract Payload for enum cases having associated value

**URL:** <https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606>\
**Category:** Pitches\
**Tags:** enums, associatedvalue\
**Created:** [August 4, 2019, 4:16pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606 "2019-08-04T16:16:24Z")\
**Posts on this page:** 20\
**Page:** 12

<div class="post-metadata">

**Author:** ![stephencelis](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/stephencelis/32/2675_2.png) [@stephencelis](https://forums.swift.org/u/stephencelis)\
**Post date:** [August 28, 2019, 2:05am UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/223 "2019-08-28T02:05:38Z")

</div>

Yeah definitely. I pitched something similar as a means of disambiguation to appease folks that are worried about such a change affecting source compatibility in general. I for one would be happy to break source compatibility for confusing edge cases that are hopefully minimal and unlikely. Ideally we can measure such changes in the source compatibility suite!

---

<div class="post-metadata">

**Author:** ![CTMacUser](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ctmacuser/32/1802_2.png) [@CTMacUser](https://forums.swift.org/u/CTMacUser)\
**Post date:** [August 28, 2019, 4:48pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/224 "2019-08-28T16:48:43Z")

</div>

> [@gwendal.roue](#):
>
> > [@ctmacuser](#):
> >
> > Aren't you off by one in your nesting?!
> 
> I don't think so... I copied the types exposed in a playground (Xcode 10.3):

That's the way the Swift compiler sees it. I'm thinking more about the view of going from a list of payload data to the enumeration type. To be consistent, a payload-less case would map to a zero-parameter function.

---

<div class="post-metadata">

**Author:** ![gwendal.roue](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/gwendal.roue/32/13992_2.png) [@gwendal.roue](https://forums.swift.org/u/gwendal.roue)\
**Post date:** [August 28, 2019, 5:42pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/225 "2019-08-28T17:42:28Z")

</div>

Yes. The empty case is special.

For me, exposing the types of static factory methods in the [original post](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/161) was a way to provide one definition of the "type of the payload" which does not quite well match the expected definition of the "type of the payload" for key paths. For `case namedValues(a: Int, b: String)`, the factory method says `(Int, String)`, when we want `(a: Int, b: String)` for key paths.

There is not only one single definition of "type of the payload", and I think it was important to reveal it as clearly as I could.

---

<div class="post-metadata">

**Author:** ![GLanza](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/glanza/32/3827_2.png) [@GLanza](https://forums.swift.org/u/GLanza)\
**Post date:** [August 28, 2019, 6:19pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/226 "2019-08-28T18:19:52Z")

</div>

> [@gwendal.roue](#):
>
> the factory method says `(Int, String)` , when we want `(a: Int, b: String)` for key paths

This would be gorgeous for my library. 😃 Unfortunately... doesn't happen as of now. 😢

---

<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:** [September 1, 2019, 3:44am UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/227 "2019-09-01T03:44:10Z")

</div>

> [@gwendal.roue](#):
>
> For `case namedValues(a: Int, b: String)` , the factory method says `(Int, String)` , when we want `(a: Int, b: String)` for key paths.

I don’t think we do.

Recall that we had that round of Evolution proposals about distinguishing parameter lists from tuples, which included changing argument labels to be regarded as part of the function name instead of the type (SE-0111). For instance `f(a: Int, b: String)` is now considered to have type `(Int, String) -> Void` and name `f(a:b:)`.

And then recall that we had that Evolution proposal to align enum cases with functions (SE-0155). The idea is that `case namedValues(a: Int, b: String)` will be considered to have name `namedValues(a:b:)`, and the payload is then `(Int, String)`.

---

<div class="post-metadata">

**Author:** ![gwendal.roue](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/gwendal.roue/32/13992_2.png) [@gwendal.roue](https://forums.swift.org/u/gwendal.roue)\
**Post date:** [September 1, 2019, 4:30am UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/228 "2019-09-01T04:30:09Z")

</div>

@xwu, I wrote "we want", but it was more a question of mine.

The letter of the law (the proposals you quote) do not talk about enum key paths, so I'm not sure they have a positive impact on the design of those. They only drive the types of the factory methods, which are not questioned in this thread.

The advantage of having the key path `\.namedValues` for `namedValues(a: Int, b: String)` expose a value of type `(a: Int, b: String)` is that it yields very naturally to composed key paths such as `\.namedValues.a`. It is DESIRE 2 in my [original post](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/161)), motivated a few lines above its definition.

Now, I've been guilty of confusion. The type of a factory method can not define a "type of payload", because it can have _several_ arguments, like `(Int, String) -> MyEnum`. Function arguments are not tuples any more: we can't feed `(Int, String) -> MyEnum` with a single value of type `(Int, String)`.

So why not `(a: Int, b: String)` for the key path?

---

<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:** [September 1, 2019, 3:48pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/229 "2019-09-01T15:48:51Z")

</div>

> [@gwendal.roue](#):
>
> So why not `(a: Int, b: String)` for the key path?

Because you can have `case foo(a: Int, a: Int, a: Int)` [but not](https://forums.swift.org/t/same-named-argument-and-tuple-labels/13757/12) `(a: Int, a: Int, a: Int)`. (This is, again, per the final state of affairs as proposed and approved, which still isn’t yet fully implemented.)

---

<div class="post-metadata">

**Author:** ![gwendal.roue](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/gwendal.roue/32/13992_2.png) [@gwendal.roue](https://forums.swift.org/u/gwendal.roue)\
**Post date:** [September 1, 2019, 4:20pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/230 "2019-09-01T16:20:49Z")

</div>

Ha, yes, you're right!

So... If one really wants to write `\.someCase.someMember` key path, one needs to define a Struct (or class) that holds the payload:

```diff
 enum MyEnum {
- case namedValues(a: Int, b: String)
+ case namedValues(Payload)
 }
+ struct Payload {
+ var a: Int
+ var b: String
+}

-enum[keyPath: \.namedValues.a] // Error: `a` is not a member of (Int, String)
+enum[keyPath: \.namedValues.a] // Int?

```

Aren't we making progress?

**Edit** : another option that we haven't studied yet is that _some_ key paths are not generated:

```swift
enum MyEnum {
    case distinctNames(a: Int, b: String)
    case identicalNames(a: Int, a: String)
}

\MyEnum.distinctNames.a // OK: KeyPath to (a: Int, b: String) tuple
\MyEnum.identicalNames.a // Compiler error

```

---

<div class="post-metadata">

**Author:** ![GLanza](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/glanza/32/3827_2.png) [@GLanza](https://forums.swift.org/u/GLanza)\
**Post date:** [September 2, 2019, 9:16am UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/231 "2019-09-02T09:16:53Z")

</div>

> [@gwendal.roue](#):
>
> **Edit** : another option that we haven't studied yet is that _some_ key paths are not generated:
> 
> ```swift
> enum MyEnum {
> case distinctNames(a: Int, b: String)
> case identicalNames(a: Int, a: String)
> }
> 
> \MyEnum.distinctNames.a // OK: KeyPath to (a: Int, b: String) tuple
> \MyEnum.identicalNames.a // Compiler error
> 
> ```

This leads me to think that maybe homonymous parameters should be disambiguated like in functions. I don't really know why this is possible in the first place.

If I do `func f(a: Int, a: Int)` I get the compiler error **Definition conflicts with previous value**

```swift
previous definition of 'a' is here
func b(a: Int, a: Int) {
       ^

```

It sounds fair that enum cases should follow the same rule... apologies if this was already discussed.

---

<div class="post-metadata">

**Author:** ![gwendal.roue](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/gwendal.roue/32/13992_2.png) [@gwendal.roue](https://forums.swift.org/u/gwendal.roue)\
**Post date:** [September 2, 2019, 9:49am UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/232 "2019-09-02T09:49:40Z")

</div>

> [@GLanza](#):
>
> It sounds fair that enum cases should follow the same rule... apologies if this was already discussed.

Discussed, but without any conclusion yet. Check @xwu's [message](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/229) above.

**Edit** : there is a conclusion, and it looks like it is implemented on master, according to the linked issue. @Slava_Pestov should know better: is `case foo(a: Int, a: Int)` about to be allowed?

---

<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:** [September 2, 2019, 11:28am UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/233 "2019-09-02T11:28:58Z")

</div>

> [@GLanza](#):
>
> If I do `func f(a: Int, a: Int)` I get the compiler error **Definition conflicts with previous value**

Sure, but that is because `a` is already defined _inside the function body_. However, you are allowed to use the same external argument label more than once, as long as they are tied to separate variables inside the function:

```swift
func f(a: Int, a b: Int) {
  print(a, b)
}

f(a: 1, a: 2) // prints "1 2"

```

---

<div class="post-metadata">

**Author:** ![GLanza](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/glanza/32/3827_2.png) [@GLanza](https://forums.swift.org/u/GLanza)\
**Post date:** [September 2, 2019, 11:56am UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/234 "2019-09-02T11:56:48Z")

</div>

I'm aware of that, but you can't do it with enum cases. In vision of KeyPaths it might be good to introduce external argument (I don't like it) or limit names to be unique.

---

<div class="post-metadata">

**Author:** ![stephencelis](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/stephencelis/32/2675_2.png) [@stephencelis](https://forums.swift.org/u/stephencelis)\
**Post date:** [September 2, 2019, 1:23pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/235 "2019-09-02T13:23:03Z")

</div>

> [@xwu](#):
>
> (This is, again, per the final state of affairs as proposed and approved, which still isn’t yet fully implemented.)

I think I've seen several core members say that these kinds of changes would have to go through evolution again if implemented, at which point we could raise any incompatibilities.

---

<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:** [September 2, 2019, 1:48pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/236 "2019-09-02T13:48:40Z")

</div>

> [@GLanza](#):
>
> I'm aware of that, but you can't do it with enum cases. In vision of KeyPaths it might be good to introduce external argument (I don't like it) or limit names to be unique.

IMHO, I'd like to deprecate the feature, and require all argument labels to be unique. Although source breaking, I expect that very few (if any!) are using this feature for anything.

---

<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:** [September 2, 2019, 2:15pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/237 "2019-09-02T14:15:31Z")

</div>

> [@stephencelis](#):
>
> I think I've seen several core members say that these kinds of changes would have to go through evolution again if implemented, at which point we could raise any incompatibilities.

I’m not aware of such a statement. What’s left to implement are a few edge cases and catching up with some technical debt; the overall model is already there.

> [@sveinhal](#):
>
> > I'm aware of that, but you can't do it with enum cases. In vision of KeyPaths it might be good to introduce external argument (I don't like it) or limit names to be unique.
> 
> IMHO, I'd like to deprecate the feature, and require all argument labels to be unique. Although source breaking, I expect that very few (if any!) are using this feature for anything.

This is entirely out of the question. For a long time now, argument labels have often been prepositions to clarify the relationship of arguments with each other at the use site; these absolutely can repeat, and this kind of use is reflected in the naming guidelines.

Enums associated types, as of SE-0155, have what are argument labels. What they do not have are internal parameter names. In fact, those labels are currently _never_ used as variable names, since the only way to get the associated values requires a pattern binding that supplies your own variable names.

During review of SE-0155, the part of proposal to require variable names in a pattern binding to match the argument label, even if only as part of a convenience feature, was **rejected** as unprecedented in Swift.

If there are going to be key paths that retrieve all associated types as a tuple, it would be inconsistent with the current design of Swift to require argument labels to function like variable names (in the sense that, as tuple labels, they could be referred to as members of the tuple). Tuples in Swift have a feature that lets users add labels at will on assignment, so I fail to see why such an inconsistent treatment would be desirable in the first place.

---

<div class="post-metadata">

**Author:** ![andrewjl](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/andrewjl/32/2995_2.png) [@andrewjl](https://forums.swift.org/u/andrewjl)\
**Post date:** [September 6, 2020, 6:36pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/238 "2020-09-06T18:36:07Z")

</div>

I've been following the various threads around enum keypaths and wanted to get a sense of what is the appropriate next step for moving fwd in the evolution process as of now.

Is there a lack of consensus on some aspect of the enum keypath ergonomics? Implementation details? Or is it a matter of needing someone to provide a formal proposal with associated implementation?

---

<div class="post-metadata">

**Author:** ![Charles\_Constant](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/charles_constant/32/13103_2.png) [@Charles\_Constant](https://forums.swift.org/u/Charles_Constant)\
**Post date:** [September 6, 2020, 8:56pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/239 "2020-09-06T20:56:06Z")

</div>

If it were up to me, I'd overhaul enums completely. The model I want is this:

```
  enum MyEnum {
     case 
          foo(label:String, Int),
          bar(Double),
          baz
  } 

```

Usage

```
  let 
     a: MyEnum = .bar(123.0),
     cpy: MyEnum = a, // .bar(123.0) case and its payload
     val: Double = a() // 123.0 payload only

  let 
     b: MyEnum = .bar(123.0),
     c: MyEnum = .bar(456.0),
     d: MyEnum = .baz

   a == b // true (both are 'bar')
   a === b // true (both 'bar' and same payload)

   a == c // true
   a === c // false (different payload)

   a == b // false
   a === b // false

```

I have essentially been using this model (via structs), and it works well. The trouble with using a struct is that the declaration of the struct involves a lot of code repetition (you have to declare both a static var and a static function overloaded with the same name for every 'case') and wasted storage for the backing id. Also, if it were built-in, Swift could warn you, when you, for example, try to compare two cases with payloads of different types.

---

<div class="post-metadata">

**Author:** ![GLanza](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/glanza/32/3827_2.png) [@GLanza](https://forums.swift.org/u/GLanza)\
**Post date:** [September 6, 2020, 9:17pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/240 "2020-09-06T21:17:45Z")

</div>

When `a` is `baz` a() should return `Void`, therefore there is no way that `val` could be declared as `Double`. The type of an associated value in an enum is uncertain. All you know for `a` is that it is a `MyEnum` which is not enough to guarantee that `val` will be `Double`.

If I remember correctly, in this thread we didn't reach an agreement on the ergonomics. But I've bundled my solution in [EnumKit](https://github.com/gringoireDM/EnumKit) and I've been using that happily since then in combination with Combine and RxSwift code. Until we get something in the language, this is so far all I need.

---

<div class="post-metadata">

**Author:** ![Charles\_Constant](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/charles_constant/32/13103_2.png) [@Charles\_Constant](https://forums.swift.org/u/Charles_Constant)\
**Post date:** [September 6, 2020, 10:45pm UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/241 "2020-09-06T22:45:04Z")

</div>

> [@GLanza](#):
>
> When `a` is `baz` a() should return `Void` , therefore there is no way that `val` could be declared as `Double` .

Why "should" it work that way? It's a design choice (and simple to implement, thanks to "@dynamicCallable").

With the paradigm I like, the programmer doesn't call the enum value with parens, unless they want its payload. Since the Payload is stored as "Any", we need to specify its type when we retrieve it. I'd also be fine if calling via parens provides an optional:

```swift
val: Double? = a() // nil, unless the Payload type matches

```

In practice, I find this matches what I _actually need to achieve_ when I use an enum with a payload. That's opposed to the way Swift works currently, which... I guess it works in theory? It certainly is unwieldy and strange, in practice, for nearly every situation where it is supposed to be useful.

_Note that, the "struct as enum" system I have been using, **does** understand the payload type, when the programmer **creates** an enum — and, with some tweaks to Swift — the Swift compiler could use that information when **retrieving** the payload, too._

PS: I haven't checked out [EnumKit](https://github.com/gringoireDM/EnumKit) yet. I suspect I also will find it far superior to what we currently have in Swift.

---

<div class="post-metadata">

**Author:** ![GLanza](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/glanza/32/3827_2.png) [@GLanza](https://forums.swift.org/u/GLanza)\
**Post date:** [September 7, 2020, 4:38am UTC](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606/243 "2020-09-07T04:38:30Z")

</div>

> [@Charles\_Constant](#):
>
> With the paradigm I like, the programmer doesn't call the enum value with parens, unless they want its payload. Since the Payload is stored as "Any", we need to specify its type when we retrieve it. I'd also be fine if calling via parens provides an optional:

```swift
let a: MyEnum = .baz // No payload
let val: Double = a() // Not legit. `a()` can be Double only if `a` is `.bar(xyz)`

```

This is what I'm trying to say. you can't have an honest `Double` from a variable of type `MyEnum` because you can't know apriori if:

1. There is an associated value to extract.
2. The associated value is in fact of type `Double` and not `(String, Int)` for example if `a` was `.foo`.

[Previous page](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606.md?page=11)

[Next page](https://forums.swift.org/t/extract-payload-for-enum-cases-having-associated-value/27606.md?page=13)
