如何返回斯威夫特数组的第一个5个对象? [英] How to return first 5 objects of Array in Swift?

查看:112
本文介绍了如何返回斯威夫特数组的第一个5个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在斯威夫特,是否有使用阵列上的高阶方法返回5第一对象的一个​​聪明的办法?
这样做的OBJ-C的方式被保存的索引,并且for循环遍历数组索引递增,直到它被5并返回新的数组。有没有办法用过滤器地图减少

In Swift, is there a clever way of using the higher order methods on Array to return the 5 first objects? The obj-c way of doing it was saving an index, and for-loop through the array incrementing index until it was 5 and returning the new array. Is there a way to do this with filter, map or reduce?

推荐答案

更新:
现在有使用 preFIX 来得到一个数组的第n个元素的可能性。检查 @ mluisbrown的回答一个解释如何使用preFIX。

Update: There is now the possibility to use prefix to get the first n elements of an array. Check @mluisbrown's answer for an explanation how to use prefix.

原来的答复:
你可以这样做很容易,而不过滤器地图减少通过只返回一个范围的数组:

Original Answer: You can do it really easy without filter, map or reduce by just returning a range of your array:

var wholeArray = [1, 2, 3, 4, 5, 6]
var n = 5

var firstFive = wholeArray[0..<n] // 1,2,3,4,5

这篇关于如何返回斯威夫特数组的第一个5个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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