如何在 Swift 中返回 Array 的前 5 个对象? [英] How to return first 5 objects of Array in Swift?

查看:105
本文介绍了如何在 Swift 中返回 Array 的前 5 个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,是否有一种巧妙的方法可以使用 Array 上的高阶方法返回前 5 个对象?这样做的 obj-c 方法是保存一个索引,然后 for 循环遍历数组递增索引直到它是 5 并返回新数组.有没有办法用 filtermapreduce 来做到这一点?

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?

推荐答案

到目前为止,获得 Swift 数组前 N 个元素的最简洁方法是使用 prefix(_ maxLength: Int):

By far the neatest way to get the first N elements of a Swift array is using prefix(_ maxLength: Int):

let someArray = [1, 2, 3, 4, 5, 6, 7]
let first5 = someArray.prefix(5) // 1, 2, 3, 4, 5

这样做的好处是边界安全.如果您传递给 prefix 的计数大于数组计数,则它只返回整个数组.

This has the benefit of being bounds safe. If the count you pass to prefix is larger than the array count then it just returns the whole array.

注意: 正如评论中指出的,Array.prefix 实际上返回的是 ArraySlice,而不是 Array>.在大多数情况下,这应该没有区别,但是如果您需要将结果分配给 Array 类型或将其传递给需要 Array 参数的方法,您将需要强制结果为 Array 类型:let first5 = Array(someArray.prefix(5))

NOTE: as pointed out in the comments, Array.prefix actually returns an ArraySlice, not an Array. In most cases this shouldn't make a difference but if you need to assign the result to an Array type or pass it to a method that's expecting an Array param you will need to force the result into an Array type: let first5 = Array(someArray.prefix(5))

这篇关于如何在 Swift 中返回 Array 的前 5 个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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