How to get the top 5 elements from an Array swift example
Sometimes, We want to return to elements from an array as a subarray.
subarray
is a slice of an array.
There are multiple ways to do this.
How to return top elements as slice array in Swift
- using the range operator in Swift
Swift provides a range operator(a…b) that contains start and end values and provides this to an array to get a subarray.
The end value of the range operator is always less than equal to the array length
Here is a valid range operator example
import Foundation
let numbers = [1, 2, 3, 4, 5,6,7,8,9]
print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(of: numbers)) // Array<Int>
var subArray = numbers[0..<3] // 1,2,3,4,5
print(subArray) // [1, 2, 3]
print(type(of: subArray)) // ArraySlice<Int>
If you provide invalid end range values, It throws Fatal error: Array index is out of range and the below code throw this error.
import Foundation
let numbers = [1, 2, 3, 4, 5,6,7,8,9]
var subArray = numbers[0..<20] // 1,2,3,4,5
- Array prefix methods
prefix methods have different variations
- prefix(n)
- prefix(upTo:n), It returns an array of elements from 0 to n-1 index elements
- prefix(through:)
import Foundation
let numbers = [1, 2, 3, 4, 5,6,7,8,9]
print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(of: numbers)) // Array<Int>
let subArray = numbers.prefix(5) // ArraySlice
print(subArray) // [1, 2, 3, 4, 5]
print(type(of: subArray)) // ArraySlice<Int>
let result=Array(subArray)
print(result) // [1, 2, 3, 4, 5]
print(type(of: result))// Array<Int>
Array prefix(upTo) example:
import Foundation
let numbers = [1, 2, 3, 4, 5,6,7,8,9]
print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(of: numbers)) // Array<Int>
let subArray = numbers.prefix(upTo:5) // ArraySlice
print(subArray) // [1, 2, 3, 4, 5]
print(type(of: subArray)) // ArraySlice<Int>
let result=Array(subArray)
print(result) // [1, 2, 3, 4, 5]
print(type(of: result))// Array<Int>
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Array<Int>
[1, 2, 3, 4, 5]
ArraySlice<Int>
[1, 2, 3, 4, 5]
Array<Int>
Array prefix(through) example:
import Foundation
let numbers = [1, 2, 3, 4, 5,6,7,8,9]
print(numbers) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(of: numbers)) // Array<Int>
let subArray = numbers.prefix(through:5) // ArraySlice
print(subArray) // [1, 2, 3, 4, 5,6]
print(type(of: subArray)) // ArraySlice<Int>
let result=Array(subArray)
print(result) // [1, 2, 3, 4, 5,6]
print(type(of: result))// Array<Int>
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Array<Int>
[1, 2, 3, 4, 5, 6]
ArraySlice<Int>
[1, 2, 3, 4, 5, 6]
Array<Int>