[swift-evolution] [Proposal] Union Type
Adrian Zubarev
adrian.zubarev at devandartist.com
Fri Jul 1 08:30:55 CDT 2016
what if OneOf<A, A>?
duplicate variable compile warning?
I already answered that question:
For example:
typealias ABC = A | B | C
typealias ABCD = ABC | D
we just use an existed type ABC to construct ABCD
But how about generic wrap?
Bikeshedding:
// we generate the boundary with `A | B` or directly OneOf<A, B>
enum OneOf<...T> {
...case $#(T)
// Bikeshedding variadic enum casses:
// we might need an index to set the value?
init(index: Int, value: T) {
self = .$index(value)
}
}
/// Usage:
/// A | B | C == OneOf<A, B, C>
func |<T, U>(_: T.Type, _: U.Type) -> OneOf<T, U>.Type {
// I also use the proposal to remove `.self` magic here
return OneOf<T, U>
}
// Here is how to merge OneOf into a single dimension
func |<...T, U>(_: OneOf<...T>.Type, _: U.Type) -> OneOf<...T, U>.Type {
// Copy and merge types into the new `OneOf` type
return OneOf<...T, U>
}
func |<T, ...U>(_: T.Type, _: OneOf<...U>.Type) -> OneOf<T, ...U>.Type {
// Copy and merge types into the new `OneOf` type
return OneOf<T, ...U>
}
func |<...T, ...U>(_: OneOf<...T>.Type, _: OneOf<...U>.Type) -> OneOf<...T, ...U>.Type {
// Copy and merge types into the new `OneOf` type
return OneOf<...T, ...U>
}
Your example will become:
typealias ABC = A | B | C // or OneOf<A, B, C>
typealias ABCD = ABC | D // merging lhs OneOf with D to OneOf<A, B, C, D>
Mission accomplished.
Again this is not a true union type because String | String != String
You’d get a OneOf enum with both first and second case as A. You still can distinguish them by the indexed label.
let test = OneOf<A, A>.init(index: 0, value: A())
switch test {
case .$1(let value)
// do something
case .$2(let value)
// do something
}
Again this is all bikeshedding of variadic generics and variadic enums!
--
Adrian Zubarev
Sent with Airmail
Am 1. Juli 2016 um 11:08:40, Cao Jiannan via swift-evolution (swift-evolution at swift.org) schrieb:
Hi all,
I'm now officially proposal the union type feature for Swift. Please see:
https://github.com/frogcjn/swift-evolution/blob/master/proposals/xxxx-union-type.md
Introduction
Add union type grammar, represents the type which is one of other types.
var stringOrURL: String | URL = "https://www.apple.com"
I would be thankful if someone support this idea and give some advice. Thanks!
--
Jiannan
_______________________________________________
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/20160701/78aefa38/attachment.html>
More information about the swift-evolution
mailing list