[swift-evolution] Proposal: floating point static min / max properties

Matthew Johnson matthew at anandabits.com
Sat Dec 5 21:14:59 CST 2015

> There’s a problem with that:
> 	 24> Int.min...Int.max
> 	fatal error: Range end index has no valid successor
> The problem is that Int.min … Int.max is actually represented as Int.min ..< Int.max.successor(), which is obviously not going to work.

That’s embarrassing.  I should have known better than to post code that should work without trying it out first!  Thanks for pointing that out.  It looks like ClosedInterval is indeed what I should have used.  

protocol ClosedIntervalType {
	static var closedInterval: ClosedInterval<Self> { get }

extension Int: ClosedIntervalType {
	static let closedInterval: ClosedInterval <Int> = Int.min…Int.max

extension Float: ClosedIntervalType {
	// not sure it would be better to use -Float. greatestFiniteMagnitude..Float. greatestFiniteMagnitude here or not
	static let closedInterval: ClosedInterval <Float> = -Float.infinity...Float.infinity

I think having something like this in the standard library would be quite useful.  All numeric types could conform as could 

> Floats don’t currently conform to the IndexType protocols because there’s no *natural* interval for them to use. nextUp/nextDown are rarely what you want in practice, while 1 breaks down at large sizes.

nextUp/nextDown may be rarely needed, they do seem to me to be a “natural” interval for floating point numbers.  Natural because successor and predecessor imply stepping through a discrete sequence of values one-by-one and any other interval would necessarily skip values.

I did run into a scenario where nextUp/nextDown were precisely what I needed which is what lead me to write a conformance of Float and Double to BidirectionalIndexType.  I didn’t actually need BidirectionalIndexType conformance - just the successor and predecessor (nextUp/nextDown) functions - it just seemed most natural to conform to the protocol that defined them functions that do precisely this.

I think it would be perfectly natural for floating point types to conform to BidirectionalIndexType but I admit it would probably not be used often.

More information about the swift-evolution mailing list