The Topic of this Thread
In this thread there are a lot of great ideas. The problem is that they discussion is too broad, so I think we should narrow it down in this particular thread. I think Union Tuples would be a really useful feature; first, though, we should discuss about adding an Either
type to the Standard Library. Because, if we don't have any insight into how Either
will be used “in the wild”, we could make bad design decisions when designing Union Tuples.
Possible design of OneOf
Nonetheless Varidadic Generics are required to make an OneOf
type. That type could combine some ideas proposed upthread. Namely, it could have:
-
A "
|
" operator, to create OneOf types - like?
forOptional
:typealias MyOneOf = Int | String
Note
The following implicit injection/projection are similar to Hashable
's
-
An injection mechanism:
let myOneOf: MyOneOf = 5 // equivalent to: let myOneOf: MyOneOf = .init(choosing: 5)
Implementation
public struct OneOf<variadic Values> { @usableFromInline internal let _value: Any @inlinable public init<Value: Values>(choosing value: Value) { self._value = value } }
-
A subscript projection mechanism:
let a: Int? = myOneOf as? Int // equivalent to: let a: Int? = myOneOf[Int.self]
Implementation
extension OneOf { @inlinable public subscript<Value: Values>(_ type: Value.Type) -> Value? { _value as? Value } }
One problem that could be quite problematic in the above is the fact that OneOf<Foo, Foo>
would be valid. Therefore, I think that an advanced variadic generics system will be required for an implementation as shown above.
Focus in Either
Despite, being amusing to think of future Union Tuple designs it is currently little more than a waste of time. For now, we should focus on Either case naming ("first"-"second", "a"-"b", "left"-"right"), projection mechanisms and default conformances.