Swift Program to Reverse a Set


In swift, a set is a unordered collection that only contain unique values. As we known that a set is an unordered collection so their is no direct way like an array to reverse the elements of the set. However you can reverse a set by converting it into an array and then apply reversed() method or any user defined function. And then convert back the result into set. Let discuss this method with the help of examples.

Example 1

In the following example, we will have a set of string type. Now we convert it into array to reverse the elements, then apply reversed() function and then convert the final result back into the set and display the output.

import Foundation
import Glibc

var myFavcolor : Set = ["Blue", "Pink", "Yellow", "Sky blue", "Red"]

// Converting set into array
var arr = Array(myFavcolor)

// Reverse the set using reversed() function
var revArr = arr.reversed()

// Convert the result back into the set
var resultantSet = Set(revArr)

print("Reversed Set is", resultantSet)

Output

Reversed Set is ["Pink", "Yellow", "Red", "Sky blue", "Blue"]

Example 2

In the following example, we will have a set of integer type. Now first we convert the set into array using Array() initialiser. Then reverse the order of the array and then convert the resultant array back into the set using Set() initialiser/constructor.

import Foundation
import Glibc

var myFavNum: Set<Int> = [12, 98, 34, 1, 34, 22, 67]

// Converting set into array
var myArr = Array(myFavNum)

let sizze = myArr.count

// Reverse the set
for i in 0..<sizze/2 {
   let j = sizze - i - 1
   let t = myArr[i]
   myArr[i] = myArr[j]
   myArr[j] = t
}

// Convert the result back into the set
let revSet = Set(myArr)

print(revSet)

Output

[12, 34, 98, 22, 67, 1]

Conclusion

So this is how we can reverse a set. In the above discussed examples, the order of the elements in the set is arbitrary so the order of the reversed set may not be necessarily same as the original set.

Updated on: 24-Apr-2023

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements