Posted at

Swift2 配列の最小値・最大値を求める

More than 3 years have passed since last update.


配列から最小値・最大値を求める方法


Swift 2

let numbers = [5, 2, 3, 9, 4, 6]

let numMin = numbers.minElement()
let numMax = numbers.maxElement()
print(numMin!,numMax!)


Swift 1.2

let numbers = [5, 2, 3, 9, 4, 6]

let numMin = numbers.reduce(Int.max, combine: { min($0, $1) })
let numMax = numbers.reduce(Int.min, combine: { max($0, $1) })
print(numMin,numMax)

参考にしたサイト

http://stackoverflow.com/questions/24036514/correct-way-to-find-max-in-an-array-in-swift