Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
suffix
set
communitycreator

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

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
}
Using the suffix() method on Sets in Swift

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.

RELATED TAGS

swift
suffix
set
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring