[swift-evolution] Adding an operator to return the "lowest common type" of two types?

William Shipley wjs at mac.com
Mon Dec 7 03:53:34 CST 2015

The problem I’m trying to solve is if I have

class LineSegmentObject {
class Wall : LineSegmentObject {
class Ray : LineSegmentObject {

And then in my code if I have

        let wallsInBounds: Set<Wall> = …
        let raysOffWalls: Set<Ray> = ...

        let unionOfAllTestedLineSegmentObjects = wallsInBounds.union(raysOffWalls)

it fails to compile. Instead I have to do the very ugly

        var unionOfAllTestedLineSegmentObjects: Set<LineSegmentObject> = (raysOffWalls as Set<LineSegmentObject>).union(wallsInBounds as Set<LineSegmentObject>)

As an aside, this also fails, surprisingly to me:

        var unionOfAllTestedLineSegmentObjects = Set<LineSegmentObject>()


So, what if we had an operator called, say, “commonType” that could take two types and return the closest type the both have in common?

Then the union operator for Set (and similar operators in Array and Dictionary) could look something like:

    public func union<S : SequenceType>(sequence: S) -> Set<commonType(Element, S.Generator.Element)>

instead of:

    public func union<S : SequenceType where S.Generator.Element == Element>(sequence: S) -> Set<Element>

[sorry if I got the syntax of defining a generic wrong up there, I’m still new to this)

So we’d automatically get an Set of LineSegments if we union a Set of Rays with a Set of Walls, which is what I’d expect.


If this type of thing doesn’t seem strict enough for you, then it could also just be a separate function, like “heterogenousUnion()” instead of “union()”.

Also, I believe this could make it a LOT easier to build heterogenous Dictionaries in code, which I actually can’t do at all in the current Swift. (Eg, creating dictionaries with arbitrary types of keys and values that you might feed to, say, SCNTechnique.) And it’d make dealing with mixed Arrays easier in a similar way.


On a scale from “Lattner" to “Lohan,” how bad an idea is this?

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

More information about the swift-evolution mailing list