[swift-evolution] Union instead of Optional
Leonardo Pessoa
me at lmpessoa.com
Mon May 16 08:25:09 CDT 2016
I can understand this proposal nite and I don't really think they're related to enums at all. You can today achieve the very same behaviour using an empty protocol.
protocol P { }
class A : P { }
class B : P { }
struct C : P { }
func test(value : P) { }
IMO, the proposed syntax will only create a shortcut for this. And we'd still need to test type and cast the to get anything useful. My question now is: is this such a common practice that justifies the shortcut?
-----Original Message-----
From: "Haravikk via swift-evolution" <swift-evolution at swift.org>
Sent: 16/05/2016 07:35 AM
To: "Austin Zheng" <austinzheng at gmail.com>
Cc: "Adrian Zubarev via swift-evolution" <swift-evolution at swift.org>; "Cao Jiannan" <frogcjn at 163.com>
Subject: Re: [swift-evolution] Union instead of Optional
> 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?
_______________________________________________
swift-evolution mailing list
swift-evolution at swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160516/7c4141f4/attachment.html>
More information about the swift-evolution
mailing list