How to find max value for Double and Float in Swift

后端 未结 7 1621
情歌与酒
情歌与酒 2020-12-23 23:55

Current learning Swift, there are ways to find max and min value for different kind of Integer like Int.max and Int.min

相关标签:
7条回答
  • 2020-12-24 00:35

    Works with swift 5

    public extension Double {
    
        /// Max double value.
        static var max: Double {
            return Double(greatestFiniteMagnitude)
        }
    
        /// Min double value.
        static var min: Double {
            return Double(-greatestFiniteMagnitude)
        }
    }
    
    0 讨论(0)
  • 2020-12-24 00:36

    All of them with using swift 5.

    0 讨论(0)
  • 2020-12-24 00:39

    AV's answer is fine, but I find those macros hard to remember and a bit non-obvious, so eventually I made Double.MIN and friends work:

    extension Double {
        static var MIN     = -DBL_MAX
        static var MAX_NEG = -DBL_MIN
        static var MIN_POS =  DBL_MIN
        static var MAX     =  DBL_MAX
    }
    

    Don't use lowercase min and max -- those symbols are used in Swift 3.

    0 讨论(0)
  • 2020-12-24 00:41

    As of Swift 3+, you should use:

    CGFloat.greatestFiniteMagnitude
    Double.greatestFiniteMagnitude
    Float.greatestFiniteMagnitude
    
    0 讨论(0)
  • 2020-12-24 00:41

    Also CGFloat.infinity, Double.infinity or just .infinity can be useful in such situations.

    0 讨论(0)
  • 2020-12-24 00:47

    Just Write

        let mxFloat = MAXFLOAT
    

    You will get maximum value of float in swif.

    0 讨论(0)
提交回复
热议问题