[swift-evolution] [Pre-pitch] "common" fields for union-style enumerations?

Daryle Walker darylew at mac.com
Sat Jul 22 19:00:51 CDT 2017


Way back in the macOS pre-X days, I remember some APIs had types like:

struct Sample1 {
int a;
int b;
float c;
};

struct Sample2 {
int a;
int b;
double d;
};

The types are supposed to be related, and it was supposed to be guaranteed that if you type-punned Sample1 to or from Sample2, the common members (“a” and “b” here) would have the same semantics. I guess it could be done like this:

struct Sample {
int a;
int b;
union {
float c;
double d;
}
};

too.

I wonder if we need something similar in Swift:

enum Sample {
@common case withFloat(a: Int, b: Int, c: Float)
@common case withDouble(a: Int, b: Int, d: Double)
}

The attribute would ensure that the shared initial members would map to the same internal offset. And, if there were no cases that didn’t have the common members, you can use them as instance level properties:

var x: Sample = .withFloat(1, 2, 3.0)
//…
assert(x.a == 1)  // Instead of “x.withFloat.a"

Good idea? Does this already exist?

— 
Daryle Walker
Mac, Internet, and Video Game Junkie
darylew AT mac DOT com 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170722/e0b61e53/attachment.html>


More information about the swift-evolution mailing list