Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
pop
communitycreator

What is the set.popFirst() 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

We use the popFirst() method in Swift to remove and return the first element of a set. It is important to remember that a set in Swift is unordered, so the first element may not be the first element on the set as we see it.

Syntax

set.popFirst()
Syntax for the "popFirst()" method

Parameter value

This method does not take any parameter values.

Return value

This method returns the first element of the set that was removed.

Code

// 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]
// pop and return first element
print(names.popFirst()!)
print(workers.popFirst()!)
print(numbers.popFirst()!)
Remove and return the first element of a set in Swift

Explanation

  • Lines 2–4: We create some set instances and initialize them with values.
  • Lines 7–9: We remove the first element of the set using the popFirst() method. Then, we return the popped or removed element.

RELATED TAGS

swift
pop
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