Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
communitycreator

What is the set.reversed() method?

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

The reversed() method is used to reverse the elements of a set. The order of elements in a set is different in Swift. If an element is in the first position of a set, it does not necessarily mean that it is the first element.

Syntax

set.reversed()
syntax for reversed()

Parameter values

This method does not take any parameter values.

Return value

This method returns an array that contains the set set with its elements reversed.

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

Explanation

  • Lines 2–4: We create some set instances and initialize them.
  • Line 7–9: We reverse the sets using the reversed() method. Then, we print the array of the reversed sets to the console.
Note: Unlike an array, a set has no order. Thus, during every execution of the code, the sets are reversed in another order.

RELATED TAGS

swift
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