{

How to get top 5 elements from an Array swift example


Sometimes, We want to return top 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 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 of 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 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>
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.