How to return first 5 objects of Array in Swift?

后端 未结 13 1762
春和景丽
春和景丽 2020-12-07 09:47

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 throug

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 10:33

    For getting the first 5 elements of an array, all you need to do is slice the array in question. In Swift, you do it like this: array[0..<5].

    To make picking the N first elements of an array a bit more functional and generalizable, you could create an extension method for doing it. For instance:

    extension Array {
        func takeElements(var elementCount: Int) -> Array {
            if (elementCount > count) {
                elementCount = count
            }
            return Array(self[0..

提交回复
热议问题