Max and min in an array of Float in Swift

后端 未结 5 1039
悲哀的现实
悲哀的现实 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:51

    Swift 4 has a .max() method for Array.

    Example:

    let floats: Array = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
    let max = floats.max()
    

    Note: max() returns an optional so there's a chance it could come back nil.

提交回复
热议问题