# Swift Program to Find Minimum Set Element Using Library Function

This tutorial will discuss how to write swift program to find minimum set element using library function.

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 find the smallest set element Swift provide an in-built function named min(). This function return minimum element from the given set. It will return nil if the given set is empty. Here the returned object of type Optional <T>. So we type cast the value into the required datatype. This function will return nil if the given set is empty.

In this function, we can also provide a predicate, due to which a comparison takes place between the elements.

Below is a demonstration of the same −

Suppose our given input is −

MySet = [78, 2, 67, 834, 45]


The desired output would be −

Smallest element = 834


## Syntax

Following is the syntax −

var minElement = mySet.min()!


## Algorithm

Following is the algorithm −

• Step 1 − Declare a set with value.

• Step 2 − Find the minimum set element using min() function and store the result into a variable −

var minElement = mySet.min()!


Here using ! We type cast the returned value into Int.

• Step 3 − Print the output

## Example 1

The following program shows how to find the minimum set element using library function.

import Foundation
import Glibc

// Creating a set
var mySet : Set = [ 2, 494, 4, 392, 58, 23, 19, 10]
print("Set:", mySet)

// Finding the smallest set element
var minElement = mySet.min()!
print("Smallest element: ", minElement)


## Output

Set: [392, 19, 4, 23, 58, 494, 2, 10]
Smallest element: 2


Here, in the above code, we have a set of Int type: [392, 19, 4, 23, 58, 494, 2, 10]. Now we find the minimum element from the set using min() −

var minElement = mySet.min()!


Here using ! We type cast the returned value of min() function into Int because it will return value of Optional Type like −

Smallest element: Optional(2)


So after using type cast the final output is −

Set: [392, 19, 4, 23, 58, 494, 2, 10]
Smallest element: 2


## Example 2

The following program shows how to find the minimum set element using library function. import Foundation

import Glibc

// Creating set of String type
let mySet : Set = ["cat", "donkey", "monkey", "bird"]
print("Set:", mySet)

// Finding the smallest set element
if let output = mySet.min(){
print("Minimum element : \(output)")
} else{
print("Set is empty")
}


## Output

Set: ["donkey", "monkey", "cat", "bird"]
Minimum element : bird


Here, in the above code, we have a set of String type: ["donkey", "monkey", "cat", "bird"]. Now we find the minimum element from the set using min() −

let output = mySet.min()


Hence the output is −

Set: ["donkey", "monkey", "cat", "bird"]
Minimum element : bird


Updated on: 12-Oct-2022

701 Views