Use FixedWidthInteger adherents as a range?

I doubt this is a serious pain point for anyone, but I find myself wanting to be able to write:

for i in UInt8 { ...

Right now I am using UInt8.min...UInt8.max, which isn't horrible, but not beautiful either. I tried extending FixedWidthInteger with an iterator, but maybe it's not possible, or more likely my swiftfu is lacking.

Anyone have any thoughts?

1 Like

Maybe this?

extension FixedWidthInteger {
    static var fullRange: ClosedRange<Self> { .min ... .max }
}

for i in UInt8.fullRange { ... }
1 Like

That's got it, thanks!

Because of type inference, you only have to write the type once. A couple options:

for i in UInt8.min ... .max { ... }

for i: UInt8 in .min ... .max { ... }

That honestly doesn't seem that bad. I'd argue it's clearer than defining a bespoke API in an extension that would require other readers to go hunt down the exact semantics.

3 Likes

I would hope for x in Int wouldn't be too confusing to people, but who knows.

I do like this construction, though.

You can't use operators on names of types but you can use them on metatypes.

extension FixedWidthInteger {
  static postfix func ...(_: Self.Type) -> ClosedRange<Self> { .min...(.max) }
}
#expect(UInt8.self... == 0...0xFF)
3 Likes