[swift-evolution] Add max/min to floating point types
Xiaodi Wu
xiaodi.wu at gmail.com
Fri Jun 10 14:38:08 CDT 2016
On Fri, Jun 10, 2016 at 1:24 PM, Darren Mo via swift-evolution <
swift-evolution at swift.org> wrote:
> Today, one can get max/min by doing:
>
> let max = Float.greatestFiniteMagnitude
> let min = -Float.greatestFiniteMagnitude
>
On review of the proposal for the new FloatingPoint, I too commented on the
lack of `max` and `min`. You've pointed out the issue with infinity. But
also, FLT_MIN (from your local friendly C universe and available in Swift,
obviously) is actually the smallest representable positive value, so
`Float.min` is of ambiguous meaning. It was therefore decided not to use
those words `max` and `min`.
>
> 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?
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160610/cd6ed5cd/attachment.html>
More information about the swift-evolution
mailing list