Swift Array suffix()

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

Example

var numbers = [2, 4, 6, 8, 10, 11, 12, 13]

// return last 3 elements print(numbers.suffix(3))
// Output: [ 11, 12, 13 ]

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()

var languages = ["Swift", "C", "Java", "Objective-C", "Kotlin"]

// return last 3 elements print(languages.suffix(3))
var prime = [9, 12, 52, 43]
// return last 2 elements print(prime.suffix(2))

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()

var names = ["Greg", "Ludovico", "Ben", "Cartman"]

// return empty array print(names.suffix(0))
// return original array print(names.suffix(4))

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.

Did you find this article helpful?