如何在Swift中找到数组的最高元素? [英] How can I find the highest elements of an Array in Swift?

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

问题描述

有人可以解释一下如何在Swift 2.2中获取数组的最高元素吗?

Can someone please explain how one would get the highest elements of an array in Swift 2.2?

例如,让我说我有以下代码:

For example lets say I have this code:

let myArray: [Int] = [2, 1, 6, 3, 5 ,7, 11]

我将如何检索该数组的3个最高值?
在这种情况下,我希望数字6、7和11。

How would i retrieve the 3 highest values of that array? In this case I'd want the numbers 6, 7 and 11.

任何帮助将不胜感激。

推荐答案

要查找 3个最高项,请对数组进行排序,并使用后缀

To find the 3 highest items, sort the array and take the last 3 items using suffix:

let myArray = [2, 1, 6, 3, 5 ,7, 11]
let highest3 = myArray.sort().suffix(3)
print(highest3)  // [6, 7, 11]

对于 3个最低项目,请使用前缀

let lowest3 = myArray.sort().prefix(3)
print(lowest3)  // [1, 2, 3]

前缀后缀具有额外的优势,即如果您的阵列中少于3个项目,它们不会崩溃。例如,如果您要求输入 .suffix(3),则包含2个项目的数组将仅返回这两个项目。

prefix and suffix have the added advantage that they do not crash if your array has fewer than 3 items. An array with 2 items for instance would just return those two items if you asked for .suffix(3).

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

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