Swift Array suffix()

The suffix() method returns the specified number of elements from the last element.

Example


suffix() Syntax

The syntax of the array suffix() method is:

array.suffix(number: Int)

Here, array is an object of the Array class.


suffix() Parameters

The suffix() method takes a single parameter:

  • number - number of elements to return from array

Note: number must be greater than or equal to 0.


suffix() Return Value

  • returns the specified number of elements from the last element.

Example 1: Swift Array suffix()

Output

["Java", "Objective-C", "Kotlin"]
[52, 43]

In the above example,

  • languages.suffix(3) - returns the last 3 elements of the languages array
  • prime.suffix(2) - returns the last 2 elements of the prime array

Example 2: Return Empty And Original Array using suffix()

Output

[]
["Greg", "Ludovico", "Ben", "Cartman"]

Here,

  • names.suffix(0) - since we have passed 0, the method returns the empty array
  • names.suffix(4) - since the number of elements to return (4) is equal to the number of elements in the array, the method returns the original array

Note: Even if the number of elements to return is greater than the number of elements in the array, the method will return the original array.