Generating Swift enums with associated values for Unions

127 views
Skip to first unread message

Nick Randall

unread,
Jan 31, 2022, 4:23:23 AM1/31/22
to FlatBuffers
Hi!

I'm using flatc to generate Swift from a lot of Union types, and am finding it quite cumbersome to map to my existing Swift structs. I know Unions are encoded as two separate fields in the binary payload, but they conceptually map perfectly onto Swift's enums with associated values and could be generated as such. I was wondering if this had been looked into before, and if there's some reason it wouldn't work. I'm happy to contribute the changes if there's no problems I'm not seeing.

Example. I've got a type like this in the schema:

union Dimension {
  absolute: AmountWithUnits,
  percent: WrappedDouble, 
}

table Item {
  height: Dimension;
  width: Dimension;
}

Basically the union is used on multiple tables for several different fields.

In my existing Swift code, I have a Dimension defined like:

enum Dimension {
  case absolute(AmountWithUnits)
  case percent(Double)
}

Flatc generates Item with a "heightType", "widthType" and generic "height" and "width" functions. These are very difficult to pass into an initialiser for the native Dimension type because they are generic, so I end up having to write multiple duplicate functions to create the native type from each pair of generated var/func.

If flatc instead generated an enum that looks like the native one, mapping it onto another type would be trivial with no duplicated switch functions.

Any insight would be great, thanks!

Nick Randall

unread,
Jan 31, 2022, 10:47:31 AM1/31/22
to FlatBuffers
Moved to Github for discussion: https://github.com/google/flatbuffers/issues/7052
Reply all
Reply to author
Forward
0 new messages