How to return first 5 objects of Array in Swift?

后端 未结 13 1757
春和景丽
春和景丽 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:27

    I slightly changed Markus' answer to update it for the latest Swift version, as var inside your method declaration is no longer supported:

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

提交回复
热议问题