Max and min in an array of Float in Swift

后端 未结 5 837
悲哀的现实
悲哀的现实 2021-01-14 17:57

According to this answer, to obtain the maximum of an array we can do:

let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, { max($0, $1) })
         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 18:42

    The solution given here https://stackoverflow.com/a/24161004/1187415 works for for all sequences of comparable elements, therefore also for an array of floats:

    let floats: Array = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
    let numMax = maxElement(floats)
    

    maxElement() is defined in the Swift library as

    /// Returns the maximum element in `elements`.  Requires:
    /// `elements` is non-empty. O(countElements(elements))
    func maxElement(elements: R) -> R.Generator.Element
    

提交回复
热议问题