[swift-evolution] Add max/min to floating point types

Darren Mo darren.mo at me.com
Fri Jun 10 13:24:11 CDT 2016


Today, one can get max/min by doing:

let max = Float.greatestFiniteMagnitude
let min = -Float.greatestFiniteMagnitude

I propose that the floating point types expose properties for max/min.

max, in particular, is used quite a lot in UI code for fixed-width layout of text. But having to spell out greatestFiniteMagnitude every time is a pain. For example…

Compare this:
extension NSTextView {
   func configureForFixedWidth() {
      minSize = NSSize.zero
      maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
      isHorizontallyResizable = false
      isVerticallyResizable = true

      textContainer?.containerSize = NSSize(width: bounds.width, height: CGFloat.greatestFiniteMagnitude)
      textContainer?.widthTracksTextView = true
   }
}

To this:
extension NSTextView {
   func configureForFixedWidth() {
      minSize = NSSize.zero
      maxSize = NSSize(width: CGFloat.max, height: CGFloat.max)
      isHorizontallyResizable = false
      isVerticallyResizable = true

      textContainer?.containerSize = NSSize(width: bounds.width, height: CGFloat.max)
      textContainer?.widthTracksTextView = true
   }
}

The latter snippet is much more understandable (and less typing). It is more understandable because users don’t have to know exactly how floating point works in order to get the equivalent of Int.max/Int.min for CGFloat.

One of the concerns with naming them max/min is that infinity/-infinity is technically the real max/min. We could name them finiteMax/finiteMin, but I think keeping the names consistent with Int et al. is important since they serve the same purpose. Besides, I think dealing with infinity is rare in real-world usage. Those that are using infinity know that it is obviously the true max.

I think adding these floating point properties is in line with Swift 3’s goals of consistency and refinement.

Thoughts?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160610/cfeceaa9/attachment.html>


More information about the swift-evolution mailing list