Pure ugliness, or the way of the future: type changing operators

So, in a fit of pique, I wrote this today:

postfix operator ¢

postfix func ¢ (value: Double) -> CGFloat {
    CGFloat(value)
}

Thus I can say:

.scale(x: geometry.size.width/self.extentsWidth¢,
       y:-(geometry.size.height/self.extentsHeight¢), anchor: .leading)

instead of

.scale(x: geometry.size.width/CGFloat(self.extentsWidth), 
       y:-(geometry.size.height/CGFloat(self.extentsHeight)), anchor: .leading)

You can probably imagine that with a large equation with values pulled from various libraries that the type fixing can get a little crazy. This is one solution to it.

That said, it's not clear to me that it's a sane solution.

In fact, as much as I am enamored of the idea of custom operators, I can't help thinking that they can be a nuisance in many cases, unless they are bring well known operators into the code.

Alas, the well known operators for changing types are characters not allowed as operators, such as L and U for long Int, Unsigned Int, or F for float.

Anyone have thoughts, or a better solution?

1 Like

I would just use a cg property:

extension BinaryFloatingPoint {
    public var cg: CGFloat { .init(self) }
}

Thus:

.scale(x: geometry.size.width/self.extentsWidth.cg,
       y:-(geometry.size.height/self.extentsHeight.cg), anchor: .leading)
4 Likes

The standard library itself once used (or still might; I haven't checked) a custom internal postfix operator ^ as shorthand for numericCast, which is essentially what you're doing here.

In the long term, Apple folks are prototyping automatic conversion between CGFloat and Double, basically a hardcoded equivalent to a type alias.

1 Like

Interesting.

I’d like to see that capability be added to the language as a library feature anyone can use, rather than special-casing it.

There are many situations where it is useful to say one type can be expressed by another. We already have that concept for literals, and it is natural to extend the notion to non-literals.

This is a right solution. Good readability, just as easy implementation. Thanks.

When I see ^ as an operator, I recall Pascal. Though not well.

I'd love to see this automatic conversion. I'm a fan of "we don't use that level of precision, but we'll work with it".