在 Swift 数组中查找最小值/最大值 [英] Find min / max value in Swift Array

查看:74
本文介绍了在 Swift 数组中查找最小值/最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一组 Swift 数值,如何找到最小值和最大值?

Given an array of Swift numeric values, how can I find the minimum and maximum values?

到目前为止,我有一个简单(但可能很昂贵)的方法:

I've so far got a simple (but potentially expensive) way:

var myMax = sort(myArray,>)[0]

以及我是如何在学校被教导这样做的:

And how I was taught to do it at school:

var myMax = 0
for i in 0..myArray.count {
    if (myArray[i] > myMax){myMax = myArray[i]}
}

有没有更好的方法可以从 Swift 中的整数数组中获取最小值或最大值?理想情况下是一行,例如 Ruby 的 .min.max.

Is there a better way to get the minimum or maximum value from an integer Array in Swift? Ideally something that's one line such as Ruby's .min and .max.

推荐答案

鉴于:

let numbers = [1, 2, 3, 4, 5]

斯威夫特 3:

numbers.min() // equals 1
numbers.max() // equals 5

斯威夫特 2:

numbers.minElement() // equals 1
numbers.maxElement() // equals 5

这篇关于在 Swift 数组中查找最小值/最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆