What is the suffix(from:) method in Swift?

Overview

The suffix(from:) method is used to return a new array that contains elements of the original array from the specified position to the end of the collection.

Syntax

arr.suffix(from : position)

Parameters

  • arr: This is the original array from which the new one will be returned.

  • position: This is the index position at which the new array elements should begin. This must be a valid index position of array arr.

Return value

The suffix(from:) method returns a new array containing the elements of arr from the specified position to the end of the array.

Example

Let’s check the code example below.

// create arrays
let numbers = [2, 1, 45, 3, 9]
let fruits = ["orange", "apple", "banana", "water-melon", "grape"]
let gnaam = ["Google", "Netflix", "Amazon", "Apple", "Meta"]
// get some elements
// and print results
print(numbers.suffix(from: 2)) // [45, 3, 9]
print(fruits.suffix(from: 1)) // ["apple", "banana", "water-melon", "grape"]
print(gnaam.suffix(from: 4)) // ["Meta"]

Explanation

  • Line 2–4: We create some arrays.
  • Line 8–10: We call the suffix(from:) method on the arrays and print the results to the console.

Free Resources