Swift program to Get the Size of Set


This tutorial will discuss how to write swift program to get the size of set.

Set is a primary collection type in Swift. It is an unordered collection which stores unique values of same data type. You are not allowed to store different type of values in the same set. A set can be mutable or immutable.

To get the size of a Set Swift provide an in-built property named count. It will return the total number of elements present in the specified count.

Below is a demonstration of the same −

Input

Suppose our given input is −

MySet = [2, 45, 67, 12, 33, 55]

Output

The desired output would be −

Size = 6

Syntax

Following is the syntax −

setName.count

Algorithm

Following is the algorithm −

  • Step 1 − Declare and initialise a Set with value.

  • Step 2 − Find the size of the set using count property −

var setSize = myNum.count
  • Step 3 − Print the output

Example 1

The following program shows how to calculate the size of a set.

import Foundation import Glibc // Creating a Set of integer Type var myNum: Set = [23, 56, 78, 9, 12, 45] // Finding the size of the Set // using count property var setSize = myNum.count print("Set: ", myNum) print("Size of the set is: ", setSize)

Output

Set: [45, 12, 23, 56, 9, 78]
Size of the set is: 6

Here, in the above code, we have a set of integer type [45, 12, 23, 56, 9, 78]. Now we find the size of the using count property −

var setSize = myNum.count

Hence the size of the set is 6.

Example 2

The following program shows how to calculate the size of a set.

import Foundation import Glibc // Creating a Set of string Type var myNames: Set = ["Susma", "Punita", "Piku", "Poonam", "Soona"] // Creating an empty Set var mySet = Set<String>() // Finding the size of the Set // using count property var setSize1 = myNames.count var setSize2 = mySet.count print("Set 1: ", myNames) print("Size of the set is: ", setSize1) print("Set 2: ", mySet) print("Size of the set is: ", setSize2)

Output

Set 1: ["Piku", "Susma", "Punita", "Soona", "Poonam"]
Size of the set is: 5
Set 2: []
Size of the set is: 0

Here, in the above code, we have two sets: myNames is of String type ["Piku", "Punita", "Poonam", "Soona", “Susma"] and mySet is an empty set. Now we find the size of the given sets using count property −

var setSize1 = myNames.count
var setSize2 = mySet.count

Hence the size of myNames is 5 and the size of setSize2 is 0.

Updated on: 20-Oct-2022

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements