What is suffix(_:) in Swift?

Overview

suffix(_:) is used to return a new array from the original array. It returns the elements up to the maximum specified length containing the original array’s final elements. In simple words, it is used to return the last elements of an array up to the number of elements specified.

Syntax

arr.suffix(maxLength)

Parameters

  • arr: This is the original array.

  • maxLength: This is the maximum number of elements to return. It must be greater or equal to zero.

Return value

This method returns a new array. It contains elements at the end of the original array arr with at most maxLength number of elements.

Example

// 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(2)) // [3, 9]
print(fruits.suffix(4)) // ["apple", "banana", "water-melon", "grape"]
print(gnaam.suffix(1)) // ["Meta"]

Explanation

  • Lines 2 to 4: We create some arrays.
  • Lines 8 to 10: We invoke the suffix(_:) method on the arrays and print the results.

Free Resources