[swift-evolution] Union instead of Optional

Haravikk swift-evolution at haravikk.me
Mon May 16 05:35:25 CDT 2016


> On 16 May 2016, at 11:17, Austin Zheng via swift-evolution <swift-evolution at swift.org> wrote:
> 
> If A, B, and C are not related via protocol or class inheritance, then there is almost nothing you can do with value. Otherwise you still need to test against the concrete type using a case statement or a if-else ladder.

I think that a case statement or similar syntax will still be needed, and the case names would just be the types themselves. This would work best with support for type-narrowing, for example:

	func someMethod(value:(A|B|C)) {
		switch (value) {
			case .A:
				value.someMethodForTypeA()
			case .B:
				value.someMethodForTypeB()
			case .C:
				value.someMethodForTypeC()
		}
	}

A union should really just be though of as a lightweight, restricted form of enum that can be declared in a quick ad-hoc fashion, similar to how tuples are a simpler form of struct.

I’m generally a +1 for the feature, but I’d be interested to hear about how well equipped the compiler is for optimising something like this. In most cases an Optional covers what I need, and in more complex cases I’d probably declare overloads for each type (i.e- someMethod(value:A), someMethod(value:B) etc.); unions could make the latter case simpler, but will the compiler produce the same code behind the scenes, i.e- by isolating what’s unique to each type?


More information about the swift-evolution mailing list