A set is a collection of unique elements. By unique, we mean no two elements in a set can be equal. Unlike sets in C++, elements of a set in Swift are not arranged in any particular order. Internally, A set in Swift uses a hash table to store elements in the set. Let us consider an example, we want to check the number of unique or different marks scored by students in a class. A set can be used to accomplish this task. Let a list containing marks be, list = [98, 80, 86, 80, 98, 98, 67, 90, 67, 84]. In list, 98 occurs thrice, 80 and 67 occur twice whereas 84, 86 and 90 occur only once. So there is a total of six unique marks scored by students in a class. We can declare a set of integers and insert these values in the set. The size of the set determines the number of unique marks scored by students.
Creating Sets
We can create an empty set by using the following syntax. This method explicitly expects a data type of the set. For example, if we want to store Int values in the set we can pass Int between angular brackets (<Int>). Likewise, we can pass Float, Character, String, Double, Bool keywords to angular bracket, etc.
Syntax:
var mySet = Set<data_type>()
Here, data_type is the type of data stored by the set (Int, Character, String, etc). Below is the program to illustrate how we can create an empty set.
Example:
Swift
// Swift program to illustrate how we can create
// an empty set of Int, Float, Double, Character
// and String type
import Foundation
import Glibc
// Creating an empty set of Int data type
var mySet1 = Set<Int>()
// Inserting elements in mySet1
mySet1.insert(10)
mySet1.insert(20)
mySet1.insert(10)
print("mySet1:", mySet1)
// Creating an empty set of Float data type
var mySet2 = Set<Float>()
// Inserting elements in mySet2
mySet2.insert(10.123)
mySet2.insert(20.123)
print("mySet2:", mySet2)
// Creating an empty set of Double data type
var mySet3 = Set<Double>()
// Inserting elements in mySet3
mySet3.insert(10.123456)
mySet3.insert(20.123456)
print("mySet3:", mySet3)
// Creating an empty set of Character data type
var mySet4 = Set<Character>()
// Inserting elements in mySet4
mySet4.insert("S")
mySet4.insert("C")
print("mySet4:", mySet4)
// Creating an empty set of String data type
var mySet5 = Set<String>()
// Inserting elements in mySet5
mySet5.insert("GeeksfoGeeks")
mySet5.insert("Geeks")
print("mySet5:", mySet5)
// Creating a empty Set of Boolean type
var mySet6 = Set<Bool>()
// Inserting elements in mySet6
mySet6.insert(true)
mySet6.insert(false)
print("mySet6:", mySet6)
Output:
mySet1: [20, 10]
mySet2: [20.123, 10.123]
mySet3: [20.123456, 10.123456]
mySet4: ["H", "i"]
mySet5: ["Geeks", "GeeksfoGeeks"]
mySet6: [true, false]
Note that we have inserted 10 twice in mySet1 but internally it was stored only once in mySet1.
Initialization of a Sets
Initializing a set basically means that we want to store some value in a set at the time of declaration. We can initialize a set by using the following methods:
Method 1: This method of initialization doesn't require explicitly passing a data type to the set. The compiler implicitly determines the data type based on the values provided to a set.
Syntax:
var mySet : Set = [value1, value2, value3,.......]
Here, mySet is the declared Set, Set is the keyword used to specify that mySet is a Set, and value1,value2, value,... are the elements belonging to mySet. Below is the implementation to illustrate how we can initialize a set.
Example:
Swift
// Swift program to illustrate how we can
// initialize a set of Int, Float, Character,
// String
// Initializing a set of integers
var mySet1: Set = [ 1, 1, 2, 3, 5 ]
// Initializing a set of floats
var mySet2: Set = [ 1.123, 2.123, 3.123, 4.123, 5.123 ]
// Initializing a set of strings
var mySet3: Set = [ "Geeks", "for", "Geeks" ]
// Initializing a set of characters
var mySet4: Set = [ "G", "e", "e", "k", "s" ]
// Print the mySet1
print("mySet1: \(mySet1)")
// Print the mySet2
print("mySet2: \(mySet2)")
// Print the mySet3
print("mySet3: \(mySet3)")
// Print the mySet4
print("mySet4: \(mySet4)")
Output:
mySet1: [3, 2, 5, 1]
mySet2: [2.123, 3.123, 5.123, 1.123, 4.123]
mySet3: ["for", "Geeks"]
mySet4: ["e", "G", "k", "s"]
Method 2: This method of initialization requires explicitly passing a data type to the set between angular brackets <>. For example, if we want to store elements of Int data-type in a set we can use <Int>. Likewise, we can pass other data types like Float, Double, Character, String, Bool, etc.
var mySet : Set<data_type> = [value1, value2, value3,.......]
Here, mySet is the declared Set, data_type is explicitly specifying that mySet can store elements of a particular data type, Set is a keyword specifies that mySet is a Set and value1,value2, value,... are the elements that belong to mySet. Below is the implementation to illustrate how we can initialize a set.
Example:
Swift
// Swift program to illustrate how to initialize a set by
// explicitly specifying the data-type of the set
// Initializing a set of integers
// by explicitly passing the data type of the set
var mySet1: Set<Int> = [ 10, 20, 20, 30, 50, 100, 20 ]
// Initializing a set of floats
// by explicitly passing the data type of the set
var mySet2: Set<Float> = [ 1.123, 2.123, 3.123, 4.123,
5.123, 6.123, 7.123 ]
// Initializing a set of doubles
// by explicitly passing the data type of the set
var mySet3: Set<Double> = [ 1.1234567, 2.1234567, 3.1234567,
4.1234567, 5.1234567, 6.1234567,
7.1234567 ]
// Initializing a set of characters
// by explicitly passing the data type of the set
var mySet4: Set<Character> = ["G", "e", "e", "k", "s"]
// Initializing a set of strings
// by explicitly passing the data type of the set
var mySet5: Set<String> = [ "GeeksforGeeks", "Java", "Python",
"Swift", "Php" ]
print("mySet1 elements are: ")
// Print mySet1 elements
for element in mySet1{
print(element)
}
print("\n")
print("mySet2 elements are: ")
// Print mySet2 elements
for element in mySet2{
print(element)
}
print("\n")
print("mySet3 elements are: ")
// Print mySet3 elements
for element in mySet3{
print(element)
}
print("\n")
print("mySet4 elements are: ")
// Print mySet4 elements
for element in mySet4{
print(element)
}
print("\n")
// Print mySet5 elements
print("mySet5 elements are: ")
// Print mySet5 elements
for element in mySet5{
print(element)
}
Output:
mySet1 elements are:
20
50
100
10
30
mySet2 elements are:
5.123
6.123
3.123
2.123
1.123
4.123
7.123
mySet3 elements are:
3.1234567
1.1234567
4.1234567
6.1234567
5.1234567
2.1234567
7.1234567
mySet4 elements are:
k
s
e
G
mySet5 elements are:
GeeksforGeeks
Java
Python
Swift
Php
Method 3: Swift provides an inbuilt method named as insert() method which is used to add elements to a Set. It takes O(1) or constant time.
Syntax:
mySet.insert(x)
Example:
Swift
// Swift program to illustrate how to add elements in set
// Creating an empty set of Int data type
var mySet = Set<String>()
// Inserting elements in mySet1
mySet.insert("GeeksforGeeks")
mySet.insert("GFG")
mySet.insert("Geeks")
print("Elements of mySet are :")
for element in mySet{
// Print a Set element
print(element)
}
Output:
Elements of mySet are :
GeeksforGeeks
Geeks
GFG
Iterating over a set
1. Using for-in loop: To iterate over a set we can take the help of the for-in loop. It directly points to values specified in a set.
Syntax:
for element in mySet {
// body
}
Here, mySet is the initialized set and element is an element of mySet.
Example:
Swift
// Swift program to illustrate how we can iterate
// over a set using for-in loop
// Initializing a Set of integers
var mySet1 : Set = [ 1, 21, 13, 4, 15, 6 ]
// Iterating over mySet1 using
// for loop
print("mySet1 elements are :")
for element in mySet1{
// Print a Set element
print(element)
}
// Next line
print("\n")
// Initializing a Set of String
var mySet2 : Set = [ "Bhuwanesh", "Kunal", "Aarush",
"Honey", "Nawal" ]
// Iterating over mySet2 using
// for loop
print("mySet2 elements are :")
for element in mySet2{
// Print a Set element
print(element)
}
Output:
mySet1 elements are :
15
21
1
4
13
6
mySet2 elements are :
Kunal
Honey
Bhuwanesh
Aarush
Nawal
2. Using index (:offsetBy:) instance method: Swift provides an instance method using which we can access set elements. This method is equivalent to accessing set elements using indices. We can iterate over the indices using a while loop and print the value present at the specified index.
Syntax:
func index(mySet.startIndex, offsetBy: index)
Parameters: mySet.startIndex is the starting index of the set and index is a non-negative integer.
Return value: Returns a value specified at the position, index
Below is the implementation to illustrate the offset instance method to iterate over a set.
Example:
Swift
// Swift program to illustrate the working of
// offset method to iterate over a set
// Initializing a set of integers
var mySet1: Set = [ 10, 3, 4, 8, 9 ]
// Initializing a variable that will
// act as an Index
var Index = 0
print("mySet1 elements: ")
// Iterating over indices
// Using while loop
while Index < mySet1.count{
// Printing elements using offset method
print(mySet1[mySet1.index(mySet1.startIndex,
offsetBy: Index)])
Index = Index + 1
}
print("\n")
// Initializing a set of floats
var mySet2: Set = [ 1.123, 3.123, 4.123, 8.123, 9.123 ]
// Initializing a variable that will
// act as an Index
Index = 0
print("mySet2 elements: ")
// Iterating over indices
// Using while loop
while Index < mySet2.count{
// Printing elements using offset method
print(mySet2[mySet2.index(mySet2.startIndex,
offsetBy: Index)])
Index = Index + 1
}
Output:
mySet1 elements:
10
4
9
3
8
mySet2 elements:
3.123
1.123
9.123
4.123
8.123
Comparing Sets
Comparing two sets means that we want to check whether they contain similar elements or not. For example, mySet1 = [9, 1, 3, 10, 12] and mySet2 = [1, 3, 10, 12, 9] are equal sets as they contain same elements whereas mySet1 = [1, 2 , 5, 4, 11] and mySet2 = [1, 2, 5, 4, 3, 11] are unequal to each other as 2 is present in mySet2 but not present in mySet1. We can compare two sets using the following methods:
1. Using contain() method: We can compare two sets by defining a custom Compare method. Follow the approach below to understand th how to compare two sets:
Approach:
1. Define a global function, Compare. The return type of this method would be bool as we want to know whether two sets are equal or not. This method accepts two sets, mySet1 and mySet2 as parameters.
2. Iterate over mySet1 using for-in loop. For each element in mySet1 check whether it is present in mySet2 using contains() method. If an element is present in mySet1 but not present in mySet2, return false.
3. Now Iterate over mySet2 using for-in loop. For each element in mySet2 check whether it is present in mySet1 using contains() method. If an element is present in mySet2 but not present in mySet1, return false.
4. Eventually, return true from the Compare function.
Below is the implementation to illustrate the above approach:
Example:
Swift
// Swift program to illustrate how we can compare
// two set using a custom function
// Defining a custom function which accepts two
// sets as a parameters
func Compare(mySet1: Set<Int>, mySet2: Set<Int>) -> Bool {
// Iterate over each element of mySet1
for element in mySet1
{
// If there is an element which is present
// in mySet1 but not present in mySet2
// return false from the Compare function
if (!mySet2.contains(element))
{
return false
}
}
for element in mySet2
{
// If there is an element which is present
// in mySet2 but not present in mySet1
// return false
if (!mySet1.contains(element))
{
return false
}
}
// Since all elements are common
// return true from the Compare function
return true
}
// Initializing a Set of Int type
var mySet1 : Set = [ 1, 3, 4, 7, 10, 12 ]
// Initializing another Set of Int type
var mySet2 : Set = [ 10, 7, 4, 3, 1, 2]
// Initializing a Set of Int type
var mySet3 : Set = [ 1, 3, 4, 7, 10, 2 ]
// Calling compare method to compare mySet1 and mySet2
print("Are myset1 and myset2 equal ? \(Compare(mySet1: mySet1, mySet2: mySet2))" )
// Calling compare method to compare mySet1 and mySet3
print("Are myset1 and myset3 equal ? \(Compare(mySet1: mySet1, mySet2: mySet3))" )
// Calling compare method to compare mySet2 and mySet3
print("Are myset2 and myset3 equal ? \(Compare(mySet1: mySet2, mySet2: mySet3))" )
Output:
Are myset1 and myset2 equal ? false
Are myset1 and myset3 equal ? false
Are myset2 and myset3 equal ? true
2. Using comparison operator ( == ): Swift provides "==" comparison operator to compare two sets directly. Internally, it checks whether sets contain the same elements. If both sets have similar elements, it returns true otherwise it returns false. Note that sets of type, mySet1 = [5, 1, 7, 8] and mySet2 = [1, 8, 7, 5] are considered to be equal as there is not any fixed order in which set elements are stored in a set and we are only concerned about whether they contain similar elements.
Syntax:
mySet1 == mySet2
Here, mySet1 and mySet2 are the sets we want to compare
Return type:
- True: if both sets contain the same elements
- False: if there is an element that is present in one set and not present in another set or vice versa.
Below is the program to illustrate how we can utilize a comparison operator to compare two sets in Swift.
Example:
Swift
// Swift program to illustrate how we can compare
// two sets using comparison operator
// Initializing a set
var mySet1: Set = [ 20.123, 50.123, 30.123, 10.123, 40.123 ]
// Initializing another set
var mySet2: Set = [ 10.123, 20.123, 30.123, 40.123, 50.123 ]
// Initializing a set
var mySet3: Set = [ 10.123, 20.123, 30.123, 40.123, 50.123, 60.123 ]
// Check whether mySet1 and mySet2 are equal
print("Are myset1 and myset2 equal ? \(mySet1 == mySet2)")
// Check whether mySet1 and mySet3 are equal
print("Are myset1 and myset3 equal ? \(mySet1 == mySet3)")
// Check whether mySet2 and mySet3 are equal
print("Are myset2 and myset2 equal ? \(mySet2 == mySet3)")
Output:
Are myset1 and myset2 equal ? true
Are myset1 and myset3 equal ? false
Are myset2 and myset2 equal ? false
Set Operations
We can perform a number of basic set operations that are union, intersection, subtraction. difference,etc. using the inbuilt methods provided in Swift.
1. Union: The Union of two sets is a set made by combining the elements of two sets. For example, consider two sets, mySet1 = {2, 10, 1, 4} and mySet2 = {10, 3, 12}. So the union set would be, myUnion = {2, 10, 1, 4, 3, 12}. In Swift, we can achieve a union of two sets with the help of the inbuilt union() method used with sets. This method requires two sets and creates a new set containing the union of specified sets.
Syntax:
mySet1.union(mySet2)
Here, mySet1 and mySet2 are initialized sets
Return type: Returns a set having elements which are either belong to a set or another set or both.
This operation takes O(n) time, where n is the length of the longest sequence.
UnionExample:
Swift
// Swift program to illustrate the working of Union operation
// Initializing a set containing multiples of 3
var mySet1: Set = [ 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 ]
// Initializing a set containing multiple of 5
var mySet2: Set = [ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 ]
// Using inbuilt union method to produce the union
// of sets containing multiples of 3 and 5
var unionOfSets = mySet1.union(mySet2).sorted()
print("Union set: \(unionOfSets)")
Output:
Union set: [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 35, 40, 45, 50]
2. Intersection: The intersection of two sets is a set having only the elements common to both sets. For example, consider two sets, mySet1 = {2, 10, 1, 4} and mySet2 = {10, 3, 12}. So the intersection set would be, myIntersection = {10}. In Swift, we can achieve an intersection of two sets with the help of the inbuilt intersection() method used with sets. This method requires two sets and creates a new set containing the intersection of specified sets.
Syntax:
mySet1.intersection(mySet2)
Here, mySet1 and mySet2 are initialized sets
Return type: Returns a set having elements that are common to both sets
This operation takes O(n) time, where n is the length of the longest sequence.
IntersectionExample:
Swift
// Swift program to illustrate the working of Intersection set operation
// Initializing a set containing multiples of 3
var mySet1: Set = [ 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 ]
// Initializing a set containing multiple of 5
var mySet2: Set = [ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 ]
// Using inbuilt intersection method to produce the
// union of sets containing multiples of 3 and 5
var intersectionOfSets = mySet1.intersection(mySet2).sorted()
print("Intersection set: \(intersectionOfSets)")
Output:
Intersection set: [15, 30]
3. Subtraction: The subtraction of two sets of the form "set1 - set2" is a set having only the elements which are present in set1 but not present in set2. For example, consider two sets, mySet1 = {2, 10, 1, 4} and mySet2 = {10, 3, 12}. So the subtraction set would be, mySubtraction = {2, 1, 4}. In Swift, we can achieve a subtraction of two sets with the help of the inbuilt subtracting() method used with sets. This method requires two sets and creates a new set containing the subtraction of specified sets.
Syntax:
mySet1.subtracting(mySet2)
Here, mySet1 and mySet2 are initialized sets
Return type: Returns a set having elements that are present in a set (mySet1) but not present in another set (mySet2).
This operation takes O(n) time, where n is the length of the longest sequence.
SubtractionExample:
Swift
// Swift program to illustrate the working of
// subtraction set operation
// Initializing a set containing multiples of 3
var mySet1: Set = [ 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 ]
// Initializing a set containing multiple of 5
var mySet2: Set = [ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 ]
// Using inbuilt subtracting method to produce the
// subtraction of sets containing multiples of 3 and 5
var subtractionOfSets = mySet1.subtracting(mySet2).sorted()
print("Subtraction set: \(subtractionOfSets)")
Output:
Subtraction set: [3, 6, 9, 12, 18, 21, 24, 27]
4. Symmetric Difference: The symmetric difference of two sets A and B is a set having all elements of both sets except the common elements. For example, consider two sets, mySet1 = {2, 10, 1, 4} and mySet2 = {10, 3, 12}. So the symmetric difference would be, mySymmetricDifference = {2, 1, 4}. In Swift, we can achieve a symmetric difference of two sets with the help of the inbuilt symmetricDifference() method used with sets. This method requires two sets and creates a new set containing the symmetric difference of specified sets.
Syntax:
mySet1.symmetricDifference(mySet2)
Here, mySet1 and mySet2 are initialized sets
Return type: Returns a set having all elements of both sets but except the common elements.
This operation takes O(n) time, where n is the length of the longest sequence.
Symmetric DifferenceExample:
Swift
// Swift program to illustrate the working of
// Symmetric Difference set operation
// Initializing a set containing multiples of 3
var mySet1: Set = [ 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 ]
// Initializing a set containing multiple of 5
var mySet2: Set = [ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 ]
// Using inbuilt symmetric difference method to
// produce the symmetric difference of sets
// containing multiples of 3 and 5
var symmetricDifferenceOfSets = mySet1.symmetricDifference(mySet2).sorted()
print("Symmetric difference set: \(symmetricDifferenceOfSets)")
Output:
Symmetric difference set: [3, 5, 6, 9, 10, 12, 18, 20, 21, 24, 25, 27, 35, 40, 45, 50]
5. Subset: A set is a subset of another set if all elements of the first set are elements of the second set. For example, mySet1 = {1, 2, 4, 3} is a subset of mySet2 = {5, 3 , 1, 2, 4}. In Swift, we can check whether a set is a subset of another set with the help of the inbuilt isSubset() method used with sets.
Syntax:
mySet1.isSubset(of: mySet2)
Here, mySet1 and mySet2 are initialized sets
Return type:
- true: If a set is a subset of another set
- false: If a set is not a subset of another set
SubsetBelow is the program to illustrate these set operations:
Example:
Swift
// Swift program to illustrate the working of Subset
// Initializing a set containing multiples of 3
var mySet1: Set = [ 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 ]
// Initializing a set containing multiple of 5
var mySet2: Set = [ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 ]
// Check mySet1 is a subset mySet2 or not
print("Is mySet1 a subset of mySet2 ?: \(mySet1.isSubset(of: mySet2))")
Output:
Is mySet1 a subset of mySet2 ?: false
Modifying Sets
To modify a set, Swift provides a number of methods associated with a set and they are:
1. remove(x): This function is used to remove an 'x' element from a Set. If the element is not already present in the Set, even then the program compiles successfully. This is a unique feature in Swift and that is why a set in Swift is sometimes advantageous over a set in other languages like C++.
Syntax:
mySet.remove(x)
2. removeFirst(): This method is used to remove the first element of a set. Since set elements are not arranged in any particular order in a set in Swift, that is why we can predict beforehand which element would be removed using this method, The time complexity of this method is Amortized constant, O(1).
Syntax:
mySet.removeFirst(x)
3. removeAll(): This function is used to remove all elements from a set. It takes O(n) time where n is the size of the set.
Syntax:
mySet.removeAll()
4. contains(x): This function is used to check whether the element x is present in the set or not. It takes O(1) time per operation. It will return true if x is present in the set, otherwise, return false if x is not present in the set.
Syntax:
mySet.contains(x)
5. count: Used to find the number of elements present in a set. It takes O(1) time per operation. For example, we are given a set, mySet = {1, 4, 5, 7, 5}. The count of mySet would be equal to 4. It will always return a non-negative integer.
Syntax:
mySet.count
6. isEmpty: Returns true if a set is empty otherwise returns false. It takes O(1) time per operation. It will return true if mySet is empty, otherwise, return false if mySet is not empty.
Syntax:
mySet.isEmpty
7. sorted(): This function temporarily arranges the elements of the set in sorted order. By temporarily, we mean after this operation the set arranges itself again in random order. It takes O(n log n) time, where n is the length of the set.
Syntax:
mySet.sorted()
8. firstIndex(x): This method is used to get the hash value of the index of element x. It takes O(1) time per operation.
Syntax:
firstIndex(x)
9. randomElement()!: Returns a random element from the set. It takes O(1) time only if the collection conforms to RandomAccessCollection otherwise it takes O(n) time, where n is the length of the collection.
Syntax:
mySet.randomElement()!
Similar Reads
Swift Tutorial Swift is a powerful general-purpose programming language developed by Apple to create iOS applications such as for iOS, macOS, watchOS, and so on. Swift code is easier to understand and write. Swift is open Source, fast, Powerful and Interoperability(Code of Swift can be used along with existing Obj
10 min read
Swift Introduction
Swift - Hello World ProgramSwift is a Programming Language used for developing iOS-based platforms like macOS, apple mobiles, apple iOS Watches, iOS TVs, iOS Keywords, iOS Mouse, and other iOS Software-based Peripherals. This language is almost 80% similar to C and Python languages. Once who is familiar with C and Python lang
2 min read
Swift - Basic SyntaxSwift is a broadly useful programming language which is created by Apple Inc. It is an amazing programming language for iOS, iPadOS, macOS, tvOS, and watchOS. It incorporates present-day highlights engineers love. Swift code is protected by plan and furthermore delivers programming that runs lightni
5 min read
Swift - KeywordsEvery programming language has some set of reserved words that are used for some internal process or represent some predefined actions such words are known as keywords or reserve words. You are not allowed to use these reserved words as a variable name, constant name, or any other identifier. But if
4 min read
Swift - LiteralsLiterals are the actual values of integer, decimal number, strings, etc. Or we can say that literals are the values of a variable or constant. We can use literals directly in a program without any computation. By default in Swift, literals don't have any type on their own. Primitive type variables c
10 min read
Swift - Constants, Variables & Print functionConstants and variables are those elements in a code linked with a particular type of value such as a number, a character, a string, etc. Constants once declared in a code cannot be changed. In comparison, variables can change at any time in a code within the scope.Declaring Constants & Variable
2 min read
Swift - OperatorsSwift is a general-purpose, multi-paradigm, and compiled programming language which is developed by Apple Inc. In Swift, an operator is a symbol that tells the compiler to perform the manipulations in the given expression. Just like other programming languages, the working of operators in Swift is a
8 min read
Swift Data Types
Swift - Data TypesData types are the most important part of any programming language. Just like other programming languages, in Swift also the variables are used to store data and what type of data is going to store in the variable is decided by their data types. As we know that variables are nothing but a reserved m
5 min read
Swift - Integer, Floating-Point NumbersIntegers are whole numbers that can be negative, zero, or positive and cannot have a fractional component. In programming, zero and positive integers are termed as âunsignedâ, and the negative ones are âsignedâ. Swift provides these two categories in the form of 8-bit, 16-bit, 32-bit and 64-bit form
2 min read
Strings in SwiftSwift 4 strings have requested an assortment of characters, for example, "Welcome GeeksforGeeks" and they are addressed by the Swift 4 information type String, which thus addresses an assortment of upsides of Character type. Strings in Swift are Unicode right and region obtuse and are intended to be
8 min read
String Functions and Operators in SwiftA string is a sequence of characters that is either composed of a literal constant or the same kind of variable. For eg., "Hello World" is a string of characters. In Swift4, a string is Unicode correct and locale insensitive. We are allowed to perform various operations on the string like comparison
10 min read
How to Concatenate Strings in Swift?In Swift, a string is a sequence of a character for example "GeeksforGeeks", "I love GeeksforGeeks", etc, and represented by a String type. A string can be mutable and immutable. When a string is assigned to a variable, such kind of string is known as a mutable string(can be modified) whereas when a
3 min read
How to Append a String to Another String in Swift?Swift language supports different types of generic collections and a string is one of them. A string is a collection of alphabets. In the Swift string, we add a string value to another string. To do this task we use the append() function. This function is used to add a string value to another string
2 min read
How to Insert a Character in String at Specific Index in Swift?Swift language supports different types of generic collections and a string is one of them. A string is a collection of alphabets. In the Swift string, we will insert a new character value into the string. To do this task we use the insert() function. This function is used to insert a new character
2 min read
How to check if a string contains another string in Swift?The Swift language supports different types of generic collections and a string is one of them. A string is a collection of alphabets. In the Swift string, we check if the specified string is present in a string or not. To do this task we use the contains() function. This function is used to check w
2 min read
How to remove a specific character from a string in Swift?Swift language supports different types of generic collections and a string is one of them. A string is a collection of alphabets. In the Swift string, we check the removal of a character from the string. To do this task we use the remove() function. This function is used to remove a character from
2 min read
Data Type Conversions in SwiftBefore we start let's see what is type conversion. Type Conversion is used to check the type of instances to find out whether it belongs to a particular class type or not using the type conversion method or approach. Basically, a Type Conversion is a method in which we can convert one instance data
5 min read
Swift - Convert String to Int SwiftSwift provides a number of ways to convert a string value into an integer value. Though, we can convert a numeric string only into an integer value. In this article, we will see the two most common methods used to convert a string to an integer value. A string is a collection of characters. Swift pr
3 min read
Swift Control Flow
Swift - Decision Making StatementsDecision-making statements are those statements in which the compiler needs to make decisions on the given conditions. If the given condition is satisfied then the set of statements is executed otherwise some other set of statements are executed. These statements always return a boolean value that i
5 min read
Swift - If StatementJust like other programming languages in Swift language also if statement is used to execute the program based on the evaluation of one or more conditions or in other words if statement is used to run a piece of code only when the given condition is true. There are also known as branch statement. Fo
3 min read
Swift - If-else StatementJust like other programming languages in Swift language also support the if-else statement. In the if-else statement, when the given condition is true then the code present inside the if condition will execute, and when the given condition is false then the code present inside the else condition wil
3 min read
Swift - If-else-if StatementIn Swift, the if-else if-else condition is used to execute a block of code among multiple options. It gives a choice between more than two alternative conditions as soon as one of the conditions is true, the statement associated with that if is executed. If all conditions are false or not satisfied
3 min read
Swift - Nested if-else StatementIn Swift, a situation comes when we have to check an if condition inside an if-else statement then a term comes named nested if-else statement. It means an if-else statement inside another if statement. Or in simple words first, there is an outer if statement, and inside it another if - else stateme
4 min read
Swift - Switch StatementIn Swift, a switch statement is a type of control mechanism that permits a program to change its flow of control and take some decisions on the basis of some conditions imposed on the value of a variable. The control flow of a program comes out of the switch statement block as soon as the matching c
10 min read
Swift - LoopsIn general, a loop is used for iteration and iteration means repetition. Using loops we can do anything n number of times. A loop can iterate infinite times until the condition fails. To break the loop generally, we write a condition. For example, if we want to print Hello GeeksforGeeks 100 times we
5 min read
Swift - While LoopJust like other programming languages, the working of the while loop in Swift is also the same. It is used to execute a target statement repeatedly as long as a given condition is true. And when the condition becomes false, the loop will immediately break and the line after the loop will execute. Wh
2 min read
Swift - Repeat While loopSometimes there's a situation that comes when we have to execute a block of many numbers of times so to do this task we use the Repeat While loop. Or we can say that in Swift, we use the Repeat While loop to execute a block of code or a set of statements repeatedly. Repeat...while loop is almost sam
3 min read
Swift - For-in LoopThe for-in loop in Swift is very similar to for loop in Python. In Python, we write for iteration in range(). Here iteration is just a variable for iteration. In swift, also we write for iteration in range. We have collections like sets, arrays, dictionaries, so we can iterate their items using a fo
6 min read
Swift - Control Statements in LoopsControl statements are used to control the flow of the loop. For example, we have written a for loop, inside the for loop we have written some 3 or 4 if conditions. Consider after satisfying 1st if condition the loop need to break, which means other of conditions should not be executed. In that case
5 min read
Swift - Break StatementThe break statement is a loop control statement that is used to end the execution of an entire control flow statement immediately when it is encountered. When the break condition is true, the loop stops its iterations, and control returns immediately from the loop to the first statement after the lo
6 min read
Swift - Fallthrough StatementJust like other languages in Swift also switch statement is very useful and powerful. It takes a value and then compare it with several possible matching pattern or we can say cases and stops its execution when it successfully found its first matching case statement and then execute the code present
4 min read
Swift - Guard StatementSwift provides a special type of statement referred to as "guard" statement. A guard statement is capable to transfer the flow of control of a program if a certain condition(s) aren't met within the program. Or we can say, if a condition expression evaluates true, then the body of the guard statemen
15 min read
Swift Functions
Calling Functions in SwiftFunctions are independent lumps of code that play out a particular undertaking. You can give a name to the function that recognizes what it does, and also the name is utilized to "call" the function to play out its errand when required. Or we can say that a function is a bunch of orders/explanations
6 min read
Swift Function Parameters and Return ValuesA function is a piece of code that is used to perform some specific task. Just like other programming languages Swift also has functions and the function has its name, parameter list, and return value. Their syntax is flexible enough to create simple as well as complex functions. All the functions i
10 min read
How to Use Variadic Parameters in Swift?A function is a block of code that is used to perform some specified task. It is reusable and saves time and resources from writing the same code again and again. The syntax of the Swift function is flexible enough to create simple as well as complex functions. A function definition contains its nam
6 min read
Swift - In Out ParametersIn Swift, a function is a collection of statements clubbed together to perform a specific task. A function may or may not contain a return type. The return type of the function decides the type of value returned by a function. For example, if we want to return an integer value from a function then t
4 min read
Swift - Nested FunctionA function is a collection of statements grouped together as a block to perform a specific task. The return type of a function decides the type of value returned by the function. For example, if we want to get an integer value from a function then the return type of the function must be Int, if we w
5 min read
Swift - Function OverloadingIn Swift, a function is a set of statements clubbed together to perform a specific task. It is declared using the "func" keyword. We can also set the return type of the function by specifying the data type followed by a return arrow ("->"). Syntax: func functionName(parameters) -> returnType {
8 min read
Closures in SwiftIn Swift, Closures are known as self-contained blocks of functionality that can be passed around and used inside your code. They are quite similar to blocks in C and Objective-C and to lambdas in other programming languages. Closures can also capture and store references to any constants and variabl
9 min read
Escaping and Non-Escaping Closures in SwiftIn Swift, a closure is a self-contained block of code that can be passed to and called from a function. Closures can be passed as arguments to functions and can be stored as variables or constants. Closures can be either escaping or non-escaping. An escaping closure is a closure that is called after
5 min read
Higher-Order Functions in SwiftHigher-order functions are functions that take other functions as arguments or return functions as their output. These functions are an important aspect of functional programming, which is a programming paradigm that focuses on the use of functions to model computation. Higher-order functions enable
10 min read
Swift Collections
Swift - ArraysAn array is one of the most powerful data structures in any programming language. It is used to store elements of similar data types. In other words, suppose we want to store a number of values that are of integer type only then in such cases we can use an array of integers, if values are of type fl
9 min read
Swift - Arrays PropertiesAn array is one of the most commonly used data types because of the benefits it provides in writing programs more efficiently. Just like other programming languages, in the Swift language, also array is a collection of similar data types. It stores data in an order list. When you assign an array to
4 min read
Swift - How to Store Values in Arrays?An array is a collection of elements having a similar data type. Normally to store a value of a particular data type we use variables. Now suppose we want to store marks of 5 students of a class. We can create 5 variables and assign marks to each of them. But for a class having 50 or more students,
4 min read
How to Remove the last element from an Array in Swift?Just like other programming languages Swift also support array. An array is an ordered generic collection that is used to store the same type of values like int, string, float, etc., you are not allowed to store the value of another type in an array, for example, you have an int type array in this a
4 min read
How to Remove the First element from an Array in Swift?Swift provides various generic collections and array is one of them. Just like other programming languages in Swift also an array is an ordered collection that is used to store the same type of values like int, string, float, etc., you are not allowed to store the value of another type in an array,
4 min read
How to count the elements of an Array in Swift?In Swift, an array is an ordered generic collection that is used to keep the same type of data like int, float, string, etc., here you are not allowed to store the value of another type. It also keeps duplicate values of the same type. An array can be mutable and immutable. When we assign an array t
2 min read
How to Reverse an Array in Swift?Swift provides various generic collections and array is one of them. Just like other programming languages, in Swift also an array is an ordered collection that is used to store the same type of values like int, string, float, etc., you are not allowed to store the value of another type in an array,
3 min read
Swift Array joined() functionSwift support different type of generic collections and array is one of them. An array is an ordered collection of the same type of values like int, string, float, etc., you are not allowed to store the value of another type in an array(for example, in a string type of array we can only store string
3 min read
How to check if the array contains a given element in Swift?The Swift language supports different types of generic collections and an array is one of them. An array is an ordered collection that is used to keep the same type of data like int, float, string, etc., in an array you are not allowed to store the value of another type. It also keeps duplicate valu
3 min read
Sorting an Array in SwiftSwift support different type of collections and array is one of them. An array is an ordered collection of the same type of values like int, string, float, etc., you are not allowed to store the value of another type in an array(for example, an int type can only store integer values, not string valu
5 min read
How to Swap Array items in Swift?Swift supports various generic collections like set, dictionary, and array. In Swift, an array is an ordered collection that is used to store the same type of values like string, int, float, etc. In an array, you are not allowed to store the value of a different type in an array, for example, if you
2 min read
How to check if an array is empty in Swift?The Swift language supports different collections like a set, array, dictionary, etc. An array is an ordered generic collection that is used to keep the same type of data like int, float, string, etc., here you are not allowed to store the value of another type. It also keeps duplicate values of the
2 min read
Swift - SetsA set is a collection of unique elements. By unique, we mean no two elements in a set can be equal. Unlike sets in C++, elements of a set in Swift are not arranged in any particular order. Internally, A set in Swift uses a hash table to store elements in the set. Let us consider an example, we want
15+ min read
Swift - Set OperationsSet is a collection of unique values. A set can be created using the initializer or the set literal syntax. A set can also be created by adding an array of unique values to an empty set. We can use a set instead of an array when we want to remove duplicate values. A set is unordered and does not mai
9 min read
How to remove first element from the Set in Swift?In Swift, a set is a generic collection that is used to store unordered values of the same type. It means you are not allowed to keep different types in the set or we can say that a string type of set can only store string data types, not int type. You can use a set instead of an array if the order
2 min read
How to remove all the elements from the Set in Swift?A set is a generic unordered collection that is used to store values of the same type. It means you are not allowed to keep different types in the set or we can say that a string type of set can only store string data types, not int type. You can use a set instead of an array if the order of the val
2 min read
How to check if the set contains a given element in Swift?Swift supports the generic collection and set is one of them. A set is used to store unordered values of the same type. It means you are not allowed to store different types in the set, e.g. a set is of int type then you can only store values of int type not of string type. A is used set instead of
3 min read
How to count the elements of a Set in Swift?Swift supports the different types of generic collections and set is one of them. A set is used to store unordered values of the same type. It means you are not allowed to keep different types in the set. You can use a set instead of an array if the order of the values is not defined or you want to
2 min read
Sorting a Set in SwiftSwift supports the generic collection and set is one of them. A set is used to store unordered values of the same type. It means you are not allowed to store different types in the set, e.g. a set is of int type then you can only store values of int type not of string type. A is used set instead of
4 min read
How to check if a set is empty in Swift?Swift supports the different types of generic collections and set is one of them. A set is used to store unordered values of the same type. It means you are not allowed to keep different types in the set. You can use a set instead of an array if the order of the values is not defined or you want to
2 min read
How to shuffle the elements of a set in Swift?A set is an unordered generic collection that is used to store elements of the same type. It means you are not allowed to keep different types in the set. You can use a set instead of an array if the order of the values is not defined or you want to store unique values. It doesn't keep duplicate val
2 min read
Swift - Difference Between Sets and ArraysAn array is a linear data structure which has contiguous memory in a single variable that can store N number of elements. For example, if we want to take 10 inputs from the user we canât initialise 10 variables. In this case you can make use of arrays. It can store N number of elements into a single
3 min read
Swift - DictionarySwift is a programming language designed to work with Apple's Cocoa and Cocoa Touch frameworks. It is intended to be a modern, safe, and flexible alternative to Objective-C. It is built with the open-source community in mind, and it is actively developed by members of the Swift community. Swift is a
9 min read
Swift - TuplesA Tuple is a constant or variable that can accommodate a group of values that can be of different data types and compounded for a single value. In easy words, a tuple is a structure that can hold multiple values of distinct data types. Tuples are generally used as return values to retrieve various d
3 min read
Swift - Iterate Arrays and DictionariesFor iterating over arrays and dictionaries we have to use the for-in, forEach loop in Swift. Both the loops support iterating over these types of data structures like arrays, dictionaries, etc. The usage of the for-in loop over data structures is very similar to the Python for loop. Both the loops a
6 min read
Swift OOPs
Swift StructuresA structure is a general-purpose building block of any code and stores variables of different data types under a single unit. Just like other programming languages in Swift you can also define the properties and methods into a structure, where the properties are the set of constants or variables tha
7 min read
Swift - Properties and its Different TypesIn Swift, properties are associated values that are stored in a class instance. OR we can say properties are the associate values with structure, class, or enumeration. There are two kinds of properties: stored properties and computed properties. Stored properties are properties that are stored in t
13 min read
Swift - MethodsMethods are functions that belong to a specific type. Instance methods, which encapsulate particular tasks and functionality for working with an instance of a given type, can be defined by classes, structures, and enumerations. Type methods, which are connected to the type itself, can also be define
5 min read
Swift - Difference Between Function and MethodSome folks use function and method interchangeably and they think function and method are the same in swift. But, function and method both are different things and both have their advantages. In the code, Both function and method can be used again but methods are one of these: classes, structs, and
4 min read
Swift - Deinitialization and How its Works?Deinitialization is the process to deallocate memory space that means when we finished our work with any memory then we will remove our pointer that is pointing to that memory so that the memory can be used for other purposes. In other words, it is the cycle to let loose unused space which was invol
4 min read
Typecasting in SwiftTypecasting in Swift is the process of determining and changing the type of a class, structure, or enumeration instance. When working with different types of objects in your code, typecasting is essential because it enables runtime type checking and safe downcasting of instances to subclass types. U
7 min read
Repeating Timers in SwiftIn Swift, a timer is a mechanism for scheduling code to run at a specified interval. A repeating timer is a type of timer that runs at a fixed interval and repeats indefinitely until it is stopped. How to Create a Repeating Timer in Swift Here are the steps to create a repeating timer in Swift: Ste
4 min read
Non Repeating Timers in SwiftDevelopers may create effective and efficient applications using a number of tools with Swift, a strong and versatile programming language. The Timer class is one such tool that enables programmers to define timed events that run at predetermined intervals. In this post, we'll go over how to make a
7 min read
Difference between Repeating and Non-Repeating timers in SwiftSwift uses timers to create recurring activities and delay the start of some processes. It is a class that was once referred to as NSTimer. This class gives a flexible method for planning tasks that will happen in the future, either once or repeatedly. You frequently encounter situations where you m
4 min read
Optional Chaining in SwiftIn Swift, optional chaining is a process for calling methods, properties, and subscripts on an optional that might currently be nil. If the optional contains a value, the method, property, or subscript is called normally. If the optional is nil, the method, property, or subscript call is ignored and
9 min read
Singleton Class in SwiftSingleton is a creational design pattern that makes sure there is just one object of its kind and provides all other code with a single point of access to it. Singletons have essentially identical benefits and drawbacks as global variables. Despite being quite useful, they prevent your code from bei
4 min read
Swift Additional Topics
Swift - Error HandlingError handling is a response to the errors faced during the execution of a function. A function can throw an error when it encounters an error condition, catch it, and respond appropriately. In simple words, we can add an error handler to a function, to respond to it without exiting the code or the
2 min read
Difference between Try, Try?, and Try! in SwiftIn every programming language, exception handling plays a crucial role in ensuring the reliability and stability of code. With the rise of Swift as a powerful and versatile programming language, developers are faced with new challenges and opportunities in managing errors and unexpected events. This
4 min read
Swift - TypealiasA variable is a named container that is used to store a value. Now each value has a type to which it belongs and is known as data type. A data type is a classification of data that tells the compiler how a programmer wants to use the data. Data types can be broadly classified into three categories,
7 min read
Important Points to Know About Java and SwiftJava is a general-purpose, class-based, object-oriented programming language and computing platform which was first developed by Sun Micro System in the year 1995. It was developed by James Gosling. It was designed to build web and desktop applications and have lesser implementation dependencies. It
3 min read
Difference between Swift Structures and C StructureSwift structures are a basic building block in the Swift programming language. They are used to group related data together in a single unit. They are similar to classes, but differ in several key ways, including: Value Types: Structures are value types, meaning that when you pass a structure to a f
4 min read
How to Build and Publish SCADE Apps to Apple and Google Stores?The two most popular platforms for distributing and promoting apps are Google Play and the Apple App Store. These two platforms are critical in the app development process since they allow developers to build mobile apps and test them on actual devices. Your applications should be created according
11 min read
6 Best iOS Project Ideas For BeginnersIf you have decided to start working on some fascinating project ideas, then you need to think first before getting started. However, itâs not an easy task to find new project ideas for learning and improving any new programming language. Those who are trying their hands-on experience with an iOS ap
8 min read