What is the set.suffix() method in Swift?

Overview

In Swift, the suffix() method is used to return a subset of a set up to the given maximum length specified.

A set is a sequence of unique elements; its order is abnormal. This means that the first element we see in a set is not necessarily the first element. This is the way sets behave in Swift. With the suffix() method, we can decide to return only the first two elements, the first five elements, and so on. This depends on the number specified.

Syntax

set.suffix(length)
The syntax for suffix() method

Parameters

This method takes a parameter, length, which represents the length or number of first n elements that should be returned. For example, if we specify it as four, the first four elements are returned.

Example

// create some sets
var names: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
var workers: Set = ["Alicia", "Bethany", "Diana"]
var numbers: Set = [1, 2, 3, 4, 5, 7, 8, 9, 10]
// create some sub sets or sub-sequences
let subNumbers = numbers.suffix(2) // first two elements
let subNames = names.suffix(4) // first four elements
// print elements returned
for number in subNumbers{
print(number)
}
for name in subNames{
print(name)
}

Explanation

  • Line 2–4: We create some sets and initialize them.
  • Line 7–8: We use the suffix() method to get some subsets of the sets.
  • Line 11–14: With the for-in loop, we print the elements of the sub-sets.

Free Resources