How to return the first 5 objects of an array in Swift?

Is there a clever way in Swift to use higher order methods in Array to return the first 5 objects? The way to do this was to save the index and for-loop through the array increment index to 5 and return a new array. Is there a way to do this with filter , map or reduce ?

+142
arrays swift
Feb 15 '15 at 15:39
source share
12 answers

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

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

This has the advantage of being safe. If the counter you pass to prefix is greater than the counter of the array, it simply returns the entire array.

NOTE: as pointed out in the comments, Array.prefix actually returns ArraySlice , not Array . In most cases, this should not matter, but if you need to assign the result to the Array type or pass it to the method waiting for the Array parameter, you will need to force the result to be converted to the Array type: let first5 = Array(someArray.prefix(5))

+350
Sep 09 '15 at 23:25
source share

Update: Now you can use prefix to get the first n elements of the array. Check out @mluisbrown's answer for an explanation of how to use the prefix.

Original answer: You can do this very easily without filter , map or reduce , simply returning the 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 
+95
Feb 15 '15 at 15:43
source share

With Swift 5, according to your needs, you can choose one of the following 6 playground codes to solve your problem.




# 1. Using subscript(_:) index

 let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array[..<5] //let arraySlice = array[0..<5] // also works //let arraySlice = array[0...4] // also works //let arraySlice = array[...4] // also works let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] 



# 2. Using the prefix(_:) method

Difficulty: O (1) if the collection matches RandomAccessCollection ; otherwise, O (k), where k is the number of elements to select at the beginning of the collection.

 let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(5) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] 

Apple claims for prefix(_:) :

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.




# 3. Using prefix(upTo:) method prefix(upTo:)

Difficulty: O (1)

 let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(upTo: 5) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] 

Apple claims for prefix(upTo:) :

Using the prefix(upTo:) method is equivalent to using a partially half-open range as the collection index. prefix(upTo:) index is preferable to prefix(upTo:) .




# 4. Using prefix(through:) method prefix(through:)

 let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let arraySlice = array.prefix(through: 4) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] 



# 5. Using removeSubrange(_:)

Difficulty: O (n), where n is the length of the collection.

 var array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] array.removeSubrange(5...) print(array) // prints: ["A", "B", "C", "D", "E"] 



# 6. Using dropLast(_:)

Difficulty: O (1) if the collection matches RandomAccessCollection ; otherwise, O (k), where k is the number of elements to delete.

 let array = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"] let distance = array.distance(from: 5, to: array.endIndex) let arraySlice = array.dropLast(distance) let newArray = Array(arraySlice) print(newArray) // prints: ["A", "B", "C", "D", "E"] 
+45
Jul 05 '17 at 16:06
source share
 let a: [Int] = [0, 0, 1, 1, 2, 2, 3, 3, 4] let b: [Int] = Array(a.prefix(5)) // result is [0, 0, 1, 1, 2] 
+25
Apr 21 '16 at 7:12
source share

SWIFT 4

Another solution:

A simple built-in solution that won't crash if your array is too short

 [0,1,2,3,4,5].enumerated().compactMap{ $0.offset < 3 ? $0.element : nil } 

But it works great with that.

 [0,1,2,3,4,5].enumerated().compactMap{ $0.offset < 1000 ? $0.element : nil } 

This usually crashes if you did this:

 [0,1,2,3,4,5].prefix(upTo: 1000) // THIS CRASHES [0,1,2,3,4,5].prefix(1000) // THIS DOESNT 
+16
Aug 04 '16 at 2:09 on
source share

To get the first 5 elements of the array, all you have to do is cut off the array in question. In Swift, you do it like this: array[0..<5] .

To make the N first elements of an array more functional and generalizable, you can create an extension method for this. For example:

 extension Array { func takeElements(var elementCount: Int) -> Array { if (elementCount > count) { elementCount = count } return Array(self[0..<elementCount]) } } 
+14
Feb 15 '15 at 16:44
source share

I modified Marcus's answer a bit to update it for the latest version of Swift, since var inside your method declaration is no longer supported:

 extension Array { func takeElements(elementCount: Int) -> Array { if (elementCount > count) { return Array(self[0..<count]) } return Array(self[0..<elementCount]) } } 
+4
Jun 09 '16 at 11:27
source share

Update for Swift 4:

 [0,1,2,3,4,5].enumerated().compactMap{ $0 < 10000 ? $1 : nil } 

For quick 3:

 [0,1,2,3,4,5].enumerated().flatMap{ $0 < 10000 ? $1 : nil } 
+1
May 24 '17 at 17:15
source share

Swift 4 preserving array types

 extension Array { func take(_ elementsCount: Int) -> [Element] { let min = Swift.min(elementsCount, count) return Array(self[0..<min]) } } 
+1
May 21 '18 at 16:25
source share

Simple and Simple

 extension Array { func first(elementCount: Int) -> Array { let min = Swift.min(elementCount, count) return Array(self[0..<min]) } } 
+1
Apr 16 '19 at 8:45
source share

For an array of objects, you can create an extension from Sequence.

 extension Sequence { func limit(_ max: Int) -> [Element] { return self.enumerated() .filter { $0.offset < max } .map { $0.element } } } 

Using:

 struct Apple {} let apples: [Apple] = [Apple(), Apple(), Apple()] let limitTwoApples = apples.limit(2) // limitTwoApples: [Apple(), Apple()] 
+1
Jul 25 '19 at 20:52
source share

Swift 4

To get the first N elements of a Swift array, you can use prefix(_ maxLength: Int) :

 Array(largeArray.prefix(5)) 
0
Aug 21 '19 at 11:02
source share



All Articles